/ webpack

webpack in real world

There are large numbers of tutorials about react and webpack, they are too simple for newcomers, if you want a productional config, you need hours for reading more documents and tutorials.

Here is my webpack config in real world.

Some points should be known:

  1. I use latest webpack for support ES6 syntax
  2. You don't have to set an object to module.exports, a function is ok, the env argument will be populate with --env=dev argument followed npm, I create a script in package.json, like this: node_modules/bin/webpack.js -d --watch --progress --env=dev
  3. multip entry points are common for medium or large sites, you always want to only build `application codes instead of library codes after changed code.
  4. name template in output.filename, you should use [chunkhash] instead of [hash], if you use [hash], every build will generate a new hash, so your application and library bundle names will changed every build.
  5. make your package.json dependencies as vendor value is good, so make sure you put right denpendencies and dev-denpendencies value, react and react-dom should in denpendencies and webpack and css-loader should in dev-denpendencies.
  6. resolve.alias is used for rules, I defined two alias, scss and static, if a path in require or import ... from xxx or other supported import methods, this path can be resolved, e.g. require('scss/main.scss'), loader can resolve scss ad path to some directory, so the loader can read that file and process by specified loaders.
  7. I used react with ES6 and sass(scss), so I need babel-loader for process js/jsx files and scss-loader for process scss files.
  8. Why there are url-loader, file-loader, css-loader and style-loader? css-loader can process url() in css files, when it finds an url, it read it and pass it to some loader, e.g. it found a png image file, it will pass to url-loader, if that file is small enough, url-loader will replace png file with base64 encoded data, you will find it is replaced by base64 data in compiled css bundle file.
    style-loader can insert css content in <style></style>, I don't need it.file-loader can hash files and replace file path with hashed path, that's great for CDN.
  9. root argument for css-loader, my css url() path is absolute path, e.g. url('/mobile/img/logo.png'), when root=static, the path will become 'static/mobile/img/logo.png', all my images are placed on static directory, and static directory are public directory on nginx.
  10. I use HtmlWebpackPlugin for generate css and js references, it will generate some <script></script> and <link> to files.
  11. webpack.optimize.CommonsChunkPlugin with two chunks, vendor is for vendor entry point, and manifest is a workaround for this plugin, it will prevent vendor chunkhash changed on every build.
  12. CleanWebpackPlugin is a plugin which can clean you dist directory before build.