Webpack

Webpack is a front-end resource loading/packaging tool. It performs static analysis according to the dependencies of modules, and then generates corresponding static resources according to the specified rules of these modules.

The configuration file

  • The entry entry tells Webpack which file to use as the entry to the project
  • Where does the output exit let WebPack put the processed packaged files
  • What different modules are used to handle various types of files

1. Build projects

  • Create the project and init it
Mkdir webpack CD webpack NPM initCopy the code
  • The new fileindex.js,run.js
// run.js function text() { var element = document.createElement('p') element.innerHTML = 'hello world' return element }  module.exports = textCopy the code
  // index.js
  var text = require('./run)
  var app = document.createElement('div')
  app.innerHTML = '<h1>HELLO WORLD</h1>'
  app.appendChild(text())
  document.body.appendChild(app)
Copy the code
  • Configuration Webpack

Install a plugin to automatically generate HTML

npm install html-webpack-plugin --save-dev

// webpack.config.js var path = require('path') var HtmlwebpackPlugin = require('html-webpack-plugin' var ROOT_PATH = path.resolve(__dirname) var APP_PATH = path.resolve(ROOT_PATH, 'app') var BUILD_PATH = path.resolve(ROOT_PATH, 'build') module.exports = {// the name of the project folder can be used directly. Output: {path: BUILD_PATH, filename: [new HtmlwebpackPlugin({title: 'Hello World app'})]}Copy the code
  • run

webpack

2. Configure hot update

  • npm install webpack-dev-server --save-dev
  • inconfigAdd configuration to
  module.exports = {
    .....
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true
    },
    .....
  }
Copy the code
  • inpackage.jsonTo add the script command
. "scripts": { "dev": "webpack-dev-server --hot --inline" }, .....Copy the code
  • runnpm run devImplement hot update

3. Add the loader

Webpack itself can only recognize JS files. For non-JS files, loader is required to convert them to JS files. Loader is a resource converter.

  • Install the loadernpm install css-loader style-loader sass-loader --save-dev
  • inconfig.jsConfigure loader in the file
  module.exports = {
    .....
    module: {
      loaders: [
        {
          test: /\.scss$/,
          loaders: ['style', 'css', 'scss'],
          include: APP_PATH
        }
      ]
    }
    .....
  }
Copy the code

4. Add the Babel

  • The installationnpm install babel-loader babel-preset-es2015 --save-dev
  • configurationconfig.jsfile
  module: {
    loaders: [
      .....
      {
        test: /\.js?$/,
        loader: 'babel',
        include: APP_PATH,
        query: {
          presets: ['es2015']
        }
      }
      .....
    ]
  }
Copy the code

Continuously updated…