webpack4.0 learning

wabpack concept

Essentially, webpack is a modern application of static JavaScript packer module (module bundler). When webpack processing applications, it recursively construct a dependency graph (dependency graph), wherein each module comprises application desired, all of these modules are then packaged into one or more of the bundle.

You can learn more about JavaScript module and webpack module from here.
Starting webpack v4.0.0, you can not introduce a configuration file. However, webpack it is still highly configurable. Before you start you need to understand the four core concepts:

Entrance (entry)
output (Output)
Loader
plug (plugins)

The following example where you can control the official website to learn, here is my own conclusion based on the official website of the study.

Started

Traditional html, is introduced using the script code depends, this will lead to global pollution. Is there a way to locally loaded in js required, the reintroduction of the dependent code.
So webpack solve our problems, the use of import, export, we need to introduce a dependent. Behind the scenes will webpack Code "translation" import-dependent program introduced by the browser can be executed.

Using a configuration file

New files in the root directory webpack.config.js,

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

Which path = require('path');is nodejs library.
1, entry representative of an entry file
2, output in accordance with the file entry, the generated output file after webpack escape. filename output file name, path to which the output files in the directory.
After downloading run the command

npm install
npx webpack

Examples link: demo3- using a configuration file

NPM script (NPM Scripts)

Use script npm

npm run build
  {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
+     "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^4.0.1",
      "webpack-cli": "^2.0.9",
      "lodash": "^4.17.5"
    }
  }

Examples link: demo4-NPM script /

Management Resources

webpack only understand their own understanding of JavaScript itself only JavaScript, if you want to deal with css, pictures, etc., need to use the loader.

loader make webpack able to deal with those non-JavaScript files (webpack itself only understand JavaScript). loader can convert all types of files is valid module webpack can handle, then you can use packaged ability webpack, and to process them.

We need to install a series of loader, by npm
CSS-Loader

npm install --save-dev style-loader css-loader

Images loader, font loader

npm install --save-dev file-loader

Data loader

npm install --save-dev csv-loader xml-loader

After installing the loader, the module configuration, you can introduce these loader, webpack reads the configuration file, parse our css files, pictures, and so on.
About some of the syntax of the loader:
the Test attributes, regular expressions, detect which files need to be converted.
When use attribute of the conversion, which should loader use.

const path = require('path');
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test:/\.(png|svg|jpg|gif)$/,
                use:[
                    'file-loader'
                ]
            },
            {
                test:/\.(woff|woff2|eot|ttf|otf)$/,
                use:[
                    'file-loader'
                ]
            },
            {
                test:/\.(csv|tsv)$/,
                use:[
                    'csv-loader'
                ]
            },
            {
                test:/\.xml$/,
                use:[
                    'xml-loader'
                ]
            }

        ]
    }
}

Examples Links: Management Resources / demo5

Output Management

Need to manually do the above introduction js, css, pictures and other resources in index.html, webpack automatically according to the configuration file import, automatic introduction of these resources to index.html
We HtmlWebpackPlugin plugin to solve this problem.
Here's what webpack plug-in usage, an array presented.
Install plug

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

webpack.config.js

const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
+   plugins: [
+     new HtmlWebpackPlugin({
+       title: 'Output Management'
+     })
+   ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

If your project has index.html under the dist directory, it will cover tune index.html, if not it will automatically generate the dist folder and generate index.html

Here Insert Picture Description
code show as below:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Output Management</title>
  </head>
  <body>
  <script type="text/javascript" src="app.bundle.js"></script><script type="text/javascript" src="print.bundle.js"></script></body>
</html>

Examples link: output management / demo6 /

Cleanup / dist folder

Here used plug-in clean-webpack-plugin, the plugin will use to clear all the files in the dist folder.
You can try to create an empty index.js in dist folder, when you run npm run buildafter, you will find index.js disappeared, leaving only the important files packaged.
Install plug

npm install clean-webpack-plugin --save-dev

webpack.config.js

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    plugins: [
+     new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Output Management'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

Now execute npm run build, then check / dist folder. If all goes well, you should now no longer see the old file, only the files generated after the building!

Develop

Use source map

The development process, after webpack packaged source code, it is difficult to track the error code, then you can use the source map, the package file, an error is in place to help us debug.
webpack.config.js

 devtool: 'inline-source-map',

Examples link: / dev / demo7-sourcemap /

Select a development tool

Here choice of development tools mean, no longer view the code each time the build operation, this is too much trouble, I hope to see is the result of the revised code, you can see the effect immediately.
There are three ways WebPACK
1, using the observation mode, commands --watch WebPACK
2, plug webpack-dev-server, the most commonly used this way.
3, plug webpack-dev-middleware

Observation mode webpack --watch
directly to modify package.json

+     "watch": "webpack --watch",

Run command npm run watch, modify your code, and then refresh the browser can see the results after modification.

This is very simple, you can use commands directly, but every time you need to refresh your browser. Here there is a better way, using plug-ins webpack-dev-server or webpack-dev-middleware auto-refresh browser
example link: Development / demo8-watch /

Use webpack-dev-server

webpack-dev-server provides a simple web server for you, and can be reloaded in real-time (live reloading). Let us set the following:

npm install --save-dev webpack-dev-server

webpack.config.js

+   devServer: {
+     contentBase: './dist'
+   },

package.json

+     "start": "webpack-dev-server --open",

Run npm start, then modify the code, after every time you save, you can see the browser automatically refreshed.
Examples link: Development / demo9_webpack-dev-server /

Use webpack-dev-middleware

webpack-dev-middleware is a container (wrapper), the file transfer it can WebPACK to a server process (server). That is where we need to take a server, where a frame express node quickly take a server, and use webpack-dev-middleware on the inside, automatic refresh.
First, install express and webpack-dev-middleware:

npm install --save-dev express webpack-dev-middleware

webpack.config.js

     output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
+     publicPath: '/'
    }

publicPath will be used in a server script

New server.js, this is the server code

package.json

+     "server": "node server.js",

Execution npm run server, open a browser, jump to HTTP: // localhost: 3000 , you can see the results of the run.
Each time you modify the code, the browser will automatically refresh.
Examples link: Development / demo10_webpack-dev-middleware /

Published 56 original articles · won praise 24 · views 30000 +

Guess you like

Origin blog.csdn.net/u014196765/article/details/99456440