After so many trials and errors, I finally have this webpack config boilerplate. It includes most common features needed for a single page application(SPA). I tried to follow the newest webpack4 best practices, so some of the configs may look different from those for webpack 2/3.
Below is the full list of features I configured:
Full Feature List
npm integration(in package.json)
1 | "scripts": { |
Note: npm start
will run the web-dev-server for local development. npm run build
will build the project in production environment.
Loaders
- babel-loader(config in .babelrc), with babel-core + babel-env-preset(for ES6) + babel-preset-react(for React JSX)
- css-loader + style-loader
css-module, need to uncomment in css-loader options:
1
2
3
4// options: {
// modules: true, // enable css modules
// localIdentName: '[name]__[local]--[hash:base64:5]' // css class names
// }Also need to modify the css files, see
Greeter.css
file for example.postcss-loader and autoprefixer plugin
plugins
- BannerPlugin(built-in plugin):
new webpack.BannerPlugin('Created by Victor Ouyang')
- HtmlWebpackPlugin: webpack will inject bundled js and css into the template you provide
- MiniCssExtractPlugin: Seperate CSS files from JS, in place
style-loader
Note: This can be used to minimize CSS in production mode, see documentation - CleanWebpackPlugin: Clean
./dist
folder every time before building
others
- source maps: use
eval-source-map
. This should only be used in local development.
Edit: Now I add source-map to production mode as well. - webpack-dev-server: By default the project is running at http://localhost:8080
Add a hash value to output file name, useful for cache:
1
2
3
4output: {
path: __dirname + "/dist", // the path to store bundled file
filename: "[name].bundle-[hash].js" // the name of bundled files
},Specify
NODE_ENV
in production mode to help some libraries to optimize