1. Introduction to WebPack

Learn about Webpack

  • What is a webpackzz
    • Webpack is a module bundler.
    • In Webpack’s view, all the front-end resource files (js/json/ CSS /img/less/…) Will be handled as modules
    • It performs static analysis based on the dependencies of modules and generates corresponding static resources
  • Understand the Loader
    • Webpack itself can only load JS/JSON modules. If you want to load other types of files (modules), you need to use the corresponding loader for conversion/loading
    • Loader itself is also a JavaScript module running in the Node.js environment
    • It is itself a function that takes the source file as an argument and returns the result of the transformation
    • Loaders are usually named in the format of xxX-loader. XXX represents the conversion functions to be performed by the loader, such as jSON-loader.
  • Configuration file (default)
    • Webpack.config. js: is a Node module that returns a configuration information object in JSON format
  • The plug-in
    • Plug-ins can perform some functions that cannot be performed by loaders.
    • The use of plug-ins is typically specified in the Plugins option of the WebPack configuration information.
    • CleanWebpackPlugin: Automatically cleans up specified folder resources
    • HtmlWebpackPlugin: Automatically generates HTML files and
    • UglifyJSPlugin: compresses JS files

2. Learning documents:

  • Webpack: webpack.github. IO /
  • Webpack2 document (English): webpack.js.org/
  • Webpack2 document (Chinese): doc.webpack-china.org/

3. Start the project

  • Initialize the project:
    • Generate a package.json file
    {"name": "webpack_test", "version": "1.0.0"}Copy the code
  • Install webpack
  • NPM install webpack -g // Global install
-npm install webpack --save-dev // Local installCopy the code

4. Compile and package your app

  • Create the entry SRC /js/ : entry.js
  • document.write(“entry.js is work”);
  • Create the main page: dist/index.html
    <script type="text/javascript" src="bundle.js"></script>
    Copy the code
  • Compile the js
    • webpack src/js/entry.js dist/bundle.js
  • View the page effect

Add js/ JSON file

  • Create a second js: SRC /js/math.js
    export function square(x) {
      return x * x;
    }
    
    export function cube(x) {
      return x * x * x;
    }
    Copy the code
  • Create a JSON file: SRC /json/data.json
    {
      "name": "Tom",
      "age": 12
    }
    Copy the code
  • Update the entry js: entry.js
    import {cube} from './math' import data from '.. // Note that data is automatically converted to a native JS object or array document.write("entry.js is work <br/>"); document.write(cube(2) + '<br/>'); document.write(JSON.stringify(data) + '<br/>')Copy the code
  • Compile the js:
    webpack src/js/entry.js dist/bundle.js
    Copy the code
  • View the page effect

6. Use webpack profiles

  • Create a webpack. Config. Js
    const path = require('path'); // Path is a built-in module for setting the path. Module. exports = {entry: './ SRC /js/entry.js', // exports = {entry: './ SRC /js/entry.js', // exports = {entry: '. Path.resolve (__dirname, 'dist') // Output file path configuration}};Copy the code
  • Configure the NPM command: package.json
    "scripts": {
      "build": "webpack"
    },
    Copy the code
  • Packaging application
    npm run build
    Copy the code

7. Package CSS and image files

  • Install style loader
NPM install csS-loader style-loader --save-dev NPM install file-loader URl-loader --save-dev Url-loader is the upper-layer encapsulation of the file-loader object and must be used together with the file-loader.Copy the code
  • Configure the loader
    module: {
      rules: [
        {
          test: /.css$/,
          use: [
            'style-loader',
            'css-loader'
          ]
        },
        {
          test: /.(png|jpg|gif)$/,
          use: [
            {
              loader: 'url-loader',
              options: {
                limit: 8192      
              }
            }
          ]
        }
      ]
    }
    Copy the code
  • Add 2 images to the app:
    • Inset: img/logo. PNG
    • Big PIC: img/big. JPG
  • Create a style file: SRC/CSS /test.css
    body { background: url('.. /img/logo.jpg') }Copy the code
  • Update the entry js: entry.js
    • import ‘.. /css/test.css’
  • Adding CSS Styles
    #box1{ width: 300px; height: 300px; background-image: url(".. /image/logo.jpg"); } #box2{ width: 300px; height: 300px; background-image: url(".. /image/big.jpg"); }Copy the code
  • Index.html to add elements
      <div id="box1"></div>
      <div id="box2"></div>
    Copy the code
  • Execute the package command:
    npm run build
    Copy the code
  • Identify problems:
    • Large images cannot be packaged into the entry.js file, and index.html is not in the build resources directory.
    • The images loaded on the page will be searched in the directory where they are located. As a result, the large image path cannot be found when the images are loaded on the page
    • The solution:
    • Use publicPath: ‘dist/js/’ // to set the path for the resources in index.html. All resources will be found in the current directory.
    • Putting index.html in dist/js/ also works.

8. Automatic compilation and packaging

  • Use the WebPack development server tool: webpack-dev-server
  • download
    • npm install –save-dev webpack-dev-server
  • Webpack configuration
     devServer: {
       contentBase: './dist'
     },
    Copy the code
  • Package configuration
    • “start”: “webpack-dev-server –open”
  • Compile the packaged application and run it
    • npm start

9. Use webPack plug-ins

  • Common plug-ins
    • Use the HTml-webpack-plugin to generate pages that import script from the template HTML
    • Clean up the dist folder using the clean-webpack-plugin
    • Use uglifyjs-webpack-plugin to compress the packaged JS file
  • download
    npm install --save-dev  html-webpack-plugin clean-webpack-plugin
    Copy the code
  • Webpack configuration
    const HtmlWebpackPlugin = require('html-webpack-plugin'); // Plugin that automatically generates HTML files const CleanWebpackPlugin = require('clean-webpack-plugin'); [new HtmlWebpackPlugin({template: './index.html'}), new CleanWebpackPlugin(['dist']),]Copy the code
  • Create the page: index.html
    <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>webpack test</title> </head> <body> <div id="app"></div> <! </body> </ HTML >Copy the code
  • Package the project
    npm run build
    npm start
    Copy the code

2. Configure the webpack.config.js file.

const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); // Plugin that automatically generates HTML files const CleanWebpackPlugin = require('clean-webpack-plugin'); Module. exports = {entry: './ SRC /js/entry.js', output: {filename: 'bundle.js', // publicPath: 'dist/js/', path: path.resolve(__dirname, 'dist/js') }, module: { rules: [ { test: /.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /.(png|jpg|gif)$/, use: [ { loader: 'url-loader', options: { limit: 8192 } } ] } ] }, plugins: [ new HtmlWebpackPlugin({template: './index.html'}), new CleanWebpackPlugin(['dist']), ] };Copy the code