BrowserifyJS
BrowserifyJS is a bundle tool. It simply bundle everything and put into a big file. It main purpose is for the web browser to work with NPM package since it can bundle the NPM package together in the bundle.js.
Because of this, it works weather you have your code written in AMD (Asynchronous Module Definition) or CommonJS (CJS) or ECMAScript Module (ESM), it simple just bundle everything.
Bundle CommonJS (CJS)
// src/logger.js
class Logger {
log(content) {
console.log(content)
}
}
module.exports = new Logger()
<!--index.html-->
<html>
<body>Example browserify</body>
<script src="build/bundle.js"></script>
</html>
// index.js
const Logger = require('./src/logger.js');
const unique = require("uniq");
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
Logger.log(unique(data));
// package.json
{
"name": "browserify-js-example",
"version": "1.0.0",
"dependencies": {
"browserify": "^17.0.0",
"uniq": "^1.0.1"
},
"scripts": {
"compile": "npx browserify index.js -o build/bundle.js"
}
}
Bundle ECMAScript Module (ESM)
Since BrowserifyJS works with CommonJS (CJS) with require()
syntax. To bundle ECMAScript Module (ESM) we need BrowserifyJS extendsion babelify
for BrowserifyJS
// package.json
{
"name": "browserify-js-example",
"version": "1.0.0",
"dependencies": {
"browserify": "^17.0.0",
"uniq": "^1.0.1"
},
"scripts": {
"compile": "npx browserify index.js -o build/bundle.js -t babelify"
},
"type": "module",
"devDependencies": {
"@babel/cli": "^7.23.0",
"@babel/core": "^7.23.2",
"@babel/preset-env": "^7.23.2",
"babelify": "^10.0.0",
"core-js": "^3.33.1"
}
}
// src/logger.js
class Logger {
log(content) {
console.log(content)
}
}
export default new Logger()
// babel.config.json
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3.6.5",
"modules": "commonjs"
}
] ],
"ignore": [
"build/**/*",
"node_modules/**/*"
]
}
// index.js
import Logger from "./src/logger";
import uniq from 'uniq';
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
Logger.log(uniq(data));
<!--index.html-->
<html>
<body>Example browserify</body>
<script src="build/bundle.js"></script>
</html>