NODE HELP

NPM fuse-box (How It Works For Developers)

Published October 24, 2024
Share:

A bundle has become a critical tool in the toolkit of any modern Node.js application. Bundlers—Webpack, Roll up, Vite—handle and package code and assets. They merge many different files into one or a few optimized bundles, improving performance by reducing the number of network requests and providing the code to be loaded effectively. Moreover, most bundles already have extras like code splitting, hot module replacement, and tree shaking that increase the experience as a developer and end user.

Bundlers are critical enablers of scalable and maintainable applications through their integration with build tools and modern JavaScript standards because they optimize resource delivery and smooth deployment workflows. In this article, we will use the NPM fuse box as a benchmark example of a bundler with the IronPDF Node.js library.

Introduction

The FuseBox NPM package is the fastest, context-driven, and most forward-thinking bundler, letting you manage and bundle your modern web application's assets with ease. Regarding developer efficiency, the FuseBox module loader has an easy configuration that aids the developer in setting things up fast to start building his project. It supports all the desired features: live reloading, code splitting, tree shaking, and so on, making development easy and the final output highly optimized.

NPM fuse-box (How It Works For Developers): Figure 1 - fuse-box

FuseBox supports many file types: JavaScript, TypeScript, CSS, and images. FuseBox module loader integrates nicely with popular frameworks and libraries. On top of this, it features an integrated plugin system that will further extend and customize FuseBox according to your project's needs. Balancing performance with ease of use, FuseBox will significantly speed up your development workflow and bundle optimized for production. FuseBox pushing it to a whole new level.

To create and configure a FuseBox project, follow these steps:

Initialize a New Node.js Project for FuseBox

Create a directory for your project, then open it in Node.js.

mkdir fusebox-project
cd fusebox-project
npm init -y
mkdir fusebox-project
cd fusebox-project
npm init -y
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'mkdir fusebox-project cd fusebox-project npm init -y
VB   C#

To Install fuse-box

Install fuse-box and other dependencies like TypeScript if you're using it.

npm install fuse-box typescript --save-dev
npm install fuse-box typescript --save-dev
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install fuse-box typescript --save-dev
VB   C#

Create FuseBox Config file

Create a fuse.js file for configuring FuseBox.

const { fusebox, sparky } = require('fuse-box');
class Context {
//node fuse dist
  getConfig() {
    return fusebox({
      target: 'browser',
      entry: 'src/index.ts',
      webIndex: {
        template: 'src/index.html',
      },
      devServer: true,
      hmr: true,
      cache: true,
      logging: {
        level: 'succinct',
      },
      sourceMap: true,
    });
  }
}
const { task, exec, rm } = sparky(Context);
task('default', async (ctx) => {
  rm('dist');
  const fuse = ctx.getConfig();
  await fuse.runDev();
});
task('dist', async (ctx) => {
  rm('dist');
  const fuse = ctx.getConfig();
  await fuse.runProd();
});
const { fusebox, sparky } = require('fuse-box');
class Context {
//node fuse dist
  getConfig() {
    return fusebox({
      target: 'browser',
      entry: 'src/index.ts',
      webIndex: {
        template: 'src/index.html',
      },
      devServer: true,
      hmr: true,
      cache: true,
      logging: {
        level: 'succinct',
      },
      sourceMap: true,
    });
  }
}
const { task, exec, rm } = sparky(Context);
task('default', async (ctx) => {
  rm('dist');
  const fuse = ctx.getConfig();
  await fuse.runDev();
});
task('dist', async (ctx) => {
  rm('dist');
  const fuse = ctx.getConfig();
  await fuse.runProd();
});
'INSTANT VB TODO TASK: The following line could not be converted:
const
	Private fusebox, sparky } = require( 'fuse-box');
Friend Class Context
'node fuse dist
  Private Function getConfig() As Private
	Return fusebox({ target: 'browser', entry: 'src/index.ts', webIndex: { template: 'src/index.html'}, devServer: True, hmr: True, cache: True, logging: { level: 'succinct'}, sourceMap: True});
  End Function
End Class
'INSTANT VB TODO TASK: The following line could not be converted:
const
	Private task, exec, rm } = sparky(Context)
task( 'default', async(ctx) =>
If True Then
	rm( 'dist');
	const fuse = ctx.getConfig()
	Await fuse.runDev()
End If
)
task( 'dist', async(ctx) =>
If True Then
	rm( 'dist');
	const fuse = ctx.getConfig()
	Await fuse.runProd()
End If
)
VB   C#

This simple example is the FuseBox configuration and usage to perform bundling and development tasks in a Node.js environment. The FuseBox plugins features allow us to add multiple plugins into the Fuxebox module.

The example first imports 'fusebox' and 'sparky' from the 'fuse-box' package, then defines a class Context with a method getConfig that returns a FuseBox configuration object. It configures the following settings: it targets the browser, it takes src/index.ts as an entry point and src/index.html as a template for the web index. Finally, the configuration of the development server comes along with the following minimal configuration options: HMR, caching, source maps, and logs very quickly.

The next step will be defining tasks using the sparky utility. The task('default') cleans the dist directory, gets the FuseBox configuration, and runs the development server. Similarly, the task('dist') cleans the dist directory but has zero configuration and instead runs the production build. The setup is quite helpful in managing development and production efficiently by automating build and serve.

Create a simple HTML File

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>FuseBox App</title>
</head>
<body>
  $bundles
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>FuseBox App</title>
</head>
<body>
  $bundles
</body>
</html>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> FuseBox App</title> </head> <body> $bundles </body> </html>
VB   C#

The above HTML template sets up a simple page for a FuseBox project. It includes character encoding and responsive design metadata. The placeholder, $bundles, is dynamically replaced by FuseBox with the correct script and style tags to ensure that bundled assets are correctly loaded, letting JavaScript and CSS load in an optimized way.

Create a TypeScript file

document.body.innerHTML = '<h1>Hello, FuseBox!</h1>';
document.body.innerHTML = '<h1>Hello, FuseBox!</h1>';
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'document.body.innerHTML = '<h1> Hello, FuseBox!</h1>';
VB   C#

This JavaScript line of code sets the HTML content of the body element of the current web page. It will substitute the content inside the

tag with a new

heading element. The text in the heading displays "Hello, FuseBox!". In essence, it is a very simple way of adding or updating content dynamically on a web page using JavaScript.

TypeScript Configuration

Generate a tsconfig.json file to hold additional configuration of the settings of TypeScript.

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"]
}
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"]
}
If True Then
  "compilerOptions":
  If True Then
	"target": "es5", "module": "commonjs", "strict": True, "esModuleInterop": True, "skipLibCheck": True, "forceConsistentCasingInFileNames": True
  End If
 , "include": ("src/**/*")
End If
VB   C#

Once done run the code. It hosts the application in localhost:4444:

NPM fuse-box (How It Works For Developers): Figure 2 - Console Output

We can view the page from the given localhost port. It will be showing like the below screenshot.

NPM fuse-box (How It Works For Developers): Figure 3 - Application Output

Introducing IronPDF: PDF Creator

For the creation, modification, conversion, and editing of PDF documents, utilize the robust Node.js package IronPDF. It is utilized in many programming-based operations related to PDFs, such as converting HTML to PDF and editing pre-existing PDFs. IronPDF is a highly useful tool for programs that need to generate and process PDFs dynamically. It offers a simple and adaptable solution to create high-quality PDF documents.

NPM fuse-box (How It Works For Developers): Figure 4 - IronPDF

Install IronPDF package

Use NPM to install packages that allow Node.js to enable IronPDF capability.

npm install @ironsoftware/ironpdf
npm install @ironsoftware/ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install @ironsoftware/ironpdf
VB   C#

Fuse-Box Bundle With IronPDF

Here's how to connect to a Node.js backend that uses IronPDF and configure FuseBox for your front-end assets.

Fuse.js file

const { fusebox} = require('fuse-box');
const fuse = fusebox({
  target: 'server',
  entry: 'src/index.ts',
  dependencies: {
    ignoreAllExternal: false,
  },
  watch: true,
  cache: false,
});
fuse.runDev();
const { fusebox} = require('fuse-box');
const fuse = fusebox({
  target: 'server',
  entry: 'src/index.ts',
  dependencies: {
    ignoreAllExternal: false,
  },
  watch: true,
  cache: false,
});
fuse.runDev();
'INSTANT VB TODO TASK: The following line could not be converted:
const
If True Then
	fusebox} = require( 'fuse-box');
const fuse = fusebox({ target: 'server', entry: 'src/index.ts', dependencies: { ignoreAllExternal: False}, watch: True, cache: False});
fuse.runDev()
VB   C#

This script establishes a FuseBox instance to group server-side scripts. It begins by importing the fusebox function from the fuse-box package and then tailors FuseBox with particular settings. The 'server' setting indicates that the output is meant for a Node.js environment, not a web browser. The entry: 'src/index.ts' points to the primary TypeScript file to initiate the bundling procedure.

The dependencies: { ignoreAllExternal: false } ensures that external dependencies are not overlooked, meaning they are added to the bundle if needed. The watch: true feature allows for automatic rebuilding of the bundle whenever the source files are updated, which helps in the development process. Finally, cache: false turns off caching, guaranteeing that the most recent updates are always part of the build. The fuse.runDev() command launches the development server with these settings.

Index.ts file

const express = require("express");
const IronPdf = require("@ironsoftware/ironpdf");
var config = IronPdf.IronPdfGlobalConfig;
config.setConfig({
  licenseKey:
    "",
});
const htmlContent = `
<html>
<head>
    <style>
        body {{ font-family: Arial, sans-serif; }}
        h1 {{ color: navy; }}
        p {{ font-size: 14px; }}
    </style>
</head>
<body>
    <h1>User Details</h1>
    <p><strong>ID:</strong> 1</p>
    <p><strong>Name:</strong> Hendry</p>
</body>
</html>
`;
// Example: Express
// On request, build each file on request and respond with its built contents
const app = express();
app.get("/generate-pdf", async (req, res) => {
  const document = IronPdf.PdfDocument;
  console.log("Requesting:generate-pdf");
  // Generate PDF document
  try {
    let result = await document.fromHtml(htmlContent);
    const pdfBuffer = await result.saveAsBuffer();
    res.setHeader("Content-Type", "application/pdf");
    res.send(pdfBuffer);
  } catch (error) {
    console.error("PDF generation error:", error);
    res.status(500).send("PDF generation error");
  }
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
const express = require("express");
const IronPdf = require("@ironsoftware/ironpdf");
var config = IronPdf.IronPdfGlobalConfig;
config.setConfig({
  licenseKey:
    "",
});
const htmlContent = `
<html>
<head>
    <style>
        body {{ font-family: Arial, sans-serif; }}
        h1 {{ color: navy; }}
        p {{ font-size: 14px; }}
    </style>
</head>
<body>
    <h1>User Details</h1>
    <p><strong>ID:</strong> 1</p>
    <p><strong>Name:</strong> Hendry</p>
</body>
</html>
`;
// Example: Express
// On request, build each file on request and respond with its built contents
const app = express();
app.get("/generate-pdf", async (req, res) => {
  const document = IronPdf.PdfDocument;
  console.log("Requesting:generate-pdf");
  // Generate PDF document
  try {
    let result = await document.fromHtml(htmlContent);
    const pdfBuffer = await result.saveAsBuffer();
    res.setHeader("Content-Type", "application/pdf");
    res.send(pdfBuffer);
  } catch (error) {
    console.error("PDF generation error:", error);
    res.status(500).send("PDF generation error");
  }
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
const express = require("express")
const IronPdf = require("@ironsoftware/ironpdf")
Dim config = IronPdf.IronPdfGlobalConfig
config.setConfig({ licenseKey:= ""})
const htmlContent = ` (Of html) (Of head) (Of style) body
If True Then
	If True Then
		font-family: Arial, sans-serif
	End If
End If
		h1
		If True Then
			If True Then
				color:
				navy
			End If
		End If
		p
		If True Then
			If True Then
				font-size: 14px
			End If
		End If
	</style> </head> (Of body) (Of h1) User Details</h1> (Of p)(Of strong) ID:</strong> 1</p> (Of p)(Of strong) Name:</strong> Hendry</p> </body> </html> `
' Example: Express
' On request, build each file on request and respond with its built contents
const app = express()
app.get("/generate-pdf", Async Sub(req, res)
	const document = IronPdf.PdfDocument
	console.log("Requesting:generate-pdf")
	Try
		Dim result As let = Await document.fromHtml(htmlContent)
		const pdfBuffer = Await result.saveAsBuffer()
		res.setHeader("Content-Type", "application/pdf")
		res.send(pdfBuffer)
	Catch e1 As [error]
		console.error("PDF generation error:", [error])
		res.status(500).send("PDF generation error")
	End Try
End Sub)
const PORT = process.env.PORT OrElse 3000
app.listen(PORT, Sub()
	console.log(`Server running on port ${PORT}`)
End Sub)
VB   C#

This script establishes a Node.js server utilizing the Express framework to generate PDFs with the IronPDF library. Initially, it includes the necessary modules: Express for the server's operations and @ironsoftware/ironpdf for handling PDF tasks. It sets up IronPDF with a license key, which is essential for creating PDFs. The HTML for the PDF is declared as a string, incorporating fundamental styling and details for the user.

Next, an Express application is developed, and a URL path /generate-pdf is established. Whenever a request is received for this path, the server employs IronPDF's PdfDocument class to produce a PDF from the given HTML content. This PDF is then stored in a buffer and returned to the client with the correct content type. Should an error arise during this procedure, the server will reply with a 500 status code and an error message. Ultimately, the server is set to listen on a designated port by default, 3000, and records a message to confirm the server's operational status.

Bundling the IronPDF script

Now we can run the fuse box bundling script.

NPM fuse-box (How It Works For Developers): Figure 5 - fuse-box module loader

It will bundle/minify the files into a separate file. With the help of the generated file, we can run the script.

NPM fuse-box (How It Works For Developers): Figure 6 - Output Bundle

Above are the minified files generated with the help of the fuse box.

NPM fuse-box (How It Works For Developers): Figure 7 - PDF Console Output

We can run the minified files as normal Node.js files.

NPM fuse-box (How It Works For Developers): Figure 8 - PDF Output

Licensing

We need a license key to make the code work without a watermark. Developers can sign up here to get a trial license. You don't have to provide a credit card to get one. When you register for a free trial, you just need to put in your email address.

Conclusion

The combination of FuseBox and IronPDF has a significant impact on making strong PDFs on the server and packaging assets on the front end. FuseBox makes it easier to build and launch web apps by grouping and improving web resources. Meanwhile, IronPDF lets you make documents straight from HTML code and is good at creating PDFs.

When used together, these tools make online apps work better and speed up the development process. They do this by making sure that managing assets and creating PDFs work together. By using IronPDF to make PDFs and FuseBox to package things, developers can build and put out apps that have cool features, work faster, and can do more with documents.

Iron Software offers various types of libraries that help us to build applications easily for various environments like Windows, Android, MAC Linux, etc.,

NEXT >
snowpack NPM (How It Works For Developers)

Ready to get started? Version: 2024.9 just released

Free npm Install View Licenses >