Webpack
Overview
It is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph from one or more entry points and then combines with dependencies needed as outputs
It allows developers to split their code into smaller chunks, which can be loaded on-demand when needed, improving performance.
Entry
An entry point indicates which module webpack should use to begin building out its internal dependency graph.
module.exports = {
entry: './path/to/my/entry/file.js',
};
Output
The output property tells webpack where to emit the bundles it creates and how to name these files.
const path = require('path');
module.exports = {
entry: './path/to/my/entry/file.js',
// to declare the output file path and name
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-first-webpack.bundle.js',
},
};
Loader
It only understands JavaScript and JSON files. Loaders allow webpack to resolve other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph.
const path = require('path');
module.exports = {
output: {
filename: 'my-first-webpack.bundle.js',
},
module: {
rules: [{ test: /\.txt$/, use: 'raw-loader' }],
},
};
Plugin
It is used to perform more advanced tasks and perform additional logic during the bundling process. as it has access to the entire compilation lifecycle and can perform actions like code optimization, asset management, and injecting environment variables.
For example: generating html file that import the link of output javascript file
const pluginName = 'ConsoleLogOnBuildWebpackPlugin';
class ConsoleLogOnBuildWebpackPlugin {
apply(compiler) {
compiler.hooks.run.tap(pluginName, (compilation) => {
// add console.log during the build process
console.log('The webpack build process is starting!');
});
}
}
module.exports = ConsoleLogOnBuildWebpackPlugin;
const path = require('path');
const ConsoleLogOnBuildWebpackPlugin = require("./myplugin");
module.exports = {
output: {
filename: 'my-first-webpack.bundle.js',
},
plugins: [
new ConsoleLogOnBuildWebpackPlugin()
]
};
Last updated
Was this helpful?