Webpacks
-
Module bundler, takes modules of the app and generates static assets into a single file.
-
Prerequisites
npm install webpack webpack-cli webpack-dev-server ...
(Install the loaders like css-loaders, etc)
- Structure of Webpack config file
- Entry
- Starting point of application, usually App.js or Index.js. Is where webpacks begins to build the application and contains imports of other modules.
- Output
- Tells webpack where to put the bundled files. Specifies location of output directory and filename.
- Transformations/Loaders and rules
- Used by webpack to transform files before being bundled. Depending on the rules the webpack will follow to process different files like css or javascript files, to make them compatible with the application.
- Plugins
- Used to perform additional tasks during the bundling process. E.g) Optimising size of whole application.
- webpack.config.js (File used to configure different settings)
- Example config file for React App
const path = require('path')
const htmlWebPackPlugin = require('html-webpack-plugin')
module.exports = {
entry: "./app/index.jsx", //Tells webpack that this is the starting file
output: {
path: path.resolve(__dirname, "dist"), //Puts everything into a folder called dist and name the bundled file with filename
filename: "index_bundle.js",
},
module: {
rules: [
///\.(js|jsx)$/ is regex
{test: /\.(js|jsx)$/, use:"babel-loader"}, //Tells Webpack, when encountering .js or .jsx file, use babel loader\
{test: /\.css$/, use: ["style-loader","css-loader"] } //Tells Webpack, for .css files, use the required loaders
]
},
resolve: { //Supports .jsx files
extensions: [".jsx","..."] //... is so that all default behaivour to work
},
plugins: [
new htmlWebPackPlugin({ //Puts html file into dist file
template: "app/index.html", //Also references the bundle file
})
],
mode: "development",
//mode: "production"
}
-
Note: Depending on how your package.json is configured, you can put "webpack" into the scripts, so the webpack command will run when you run a script.
-
You can run with:
npm webpack
npm webpack-serve (Auto rebuilds app when changes are made)
Babel
- An open-source Javascript compiler that is used to translate ES6 code into older compatible Javascript that can be run on older browswers
- You can see from the webpack example, babel-loader is used.