Webpack
Webpack is a bundle tool like BrowserifyJS. However it works much better out of the box.
For example in BrowserifyJS to bundle ECMAScript Module (ESM), you need to use Babelify.
However, in webpack it's basically out of the box
Webpack basically use Node.js
to bundle our file. Therefore, the webpack.config.js
will have CommonJS (CJS) syntax:
const path = require('path');
module.exports = {
// a json object of webpack settings
};
Details can be found here: Concepts | webpack
Given the same example:
// Logger.js in CommonJS
class Logger {
log(content) {
console.log(content)
}
}
module.exports = new Logger()
// index.js in the most random form as possible
var unique = require('uniq');
import Logger from "./src/logger";
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
Logger.log(unique(data));
<html>
<body>Example webpack</body>
<script type="module" src="build/index.js"></script>
</html>
// package.json
{
"scripts": {
"build": "webpack"
},
"dependencies": {
"uniq": "^1.0.1"
},
"devDependencies": {
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4"
}
}
// webpack.config.js
const path = require('path')
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, "build"),
filename: "index.js"
},
mode: 'production'
}
It will just work after npm run build