- Initialize
package.json
"scripts": {
"build": "webpack",
"watch": "webpack --watch"
},
npm run buildruns Webpacknpm run watchruns Webpack with the--watchflag
const path = require("path");
module.exports = {
entry: './src/index.js',
output: {
filename: "bundle.js",
path: path.join(__dirname, "build")
}
}entryis the first file in the dependency graphpathis always an absolute path- Defaults to
./dist
- Defaults to
- Here, we join the current directory
__dirnamewith a directory namedbuild
- Webpack starts from the entry file and goes and looks for each
import/exportstatement and bundles them into required module dependencies
- Webpack allows any type of asset to be treated as a module and transformed
- In the end, the asset is converted back to JS and added back to the dependency graph
// webpack.config.js
module.exports = {
...,
module: {
rules: [
{
test: /\.js$/,
use:"babel-loader"
},
{
test: /\.css$/,
use: [
"style-loader",
"css-loader"
]
}
]
}
}testtells Webpack to match files against Regex and perform a transformation- The transformation is a loader
styleLoader(cssLoader(source));use: [
"style-loader",
"css-loader"
]- Loaders can only apply changes to a single file right before it can be added to the dependency graph
- Plugins do what loaders cannot (ex. change multiple files, create bundles)
class ExamplePlugin {
apply(compiler) {
compiler.plugin("run", (compiler, callback) => {
console.log('webpack is running');
callback();
});
}
}
module.exports = ExamplePlugin;// webpack.config.js
const ExamplePlugin = require("./ExamplePlugin.js");
module.exports = {
...,
plugins: [
new ExamplePlugin()
]
}- The root of the webpack dependency graph
- How and where to put the bundles
- How to treat folders before they are added to the dependency graph
- Allows any asset to be treated like a module
- Any other functionality
- Class based, extremely customizable
Uncaught SyntaxError: Cannot use import statement outside a module
- using imports and exports with multiple JS files
- there can only be one js file for our html :)
- webpack bundles all the modules up into 1 entry point
- also cleans out all the unnecessary stuff; keeps the goods
- (ex. outputting the function body code instead of importing the function)
- Install Webpack
- Put all the js files inside a
srcfolder npx webpackto compile oursrcfiles- Check
distfor our outputmain.js
In webpack.config.js, we can add source maps which helps with debugging (get the actual source of a piece of code in the bundle)
module.exports = {
module: { ... },
devtool: "source-map"
}- Hot reloading
npm i -D webpack-dev-server