The installation

npm install webpack webpack-cli -g  // Global installation
npm install webpack webpack-cli -D  // Partial development depends on installation
Copy the code

use

  • The default entry is SRC /index.js

  • O dist/main. Js

  • Use global dependency packaging

  1. webpack
  • Local dependency packaging
  1. npx webpack
  2. ./node_modules/.bin/webpack
  3. NPM Run build # recommended

package.json

 "scripts": {
    "build": "webpack"
  }
Copy the code

configuration

Method 1. Do not use a configuration file to configure simple parameters using the CLI. For details, see API/ COMMAND Line Interface/Usage

2. Use the configuration file

  • Add webpack.config.js to the root directory
  • Specify the file as a configuration file

package.json

"scripts": {
    "build": "webpack --config prod.config.js"
  }
Copy the code

Custom entrances and exits

const path = require('path')

module.exports = {
  entry: "./src/main.js".// Specify the entry
  output: {
    filename: 'build.js'./ / file name
    path: path.resolve(__dirname, 'build') // The output directory is an absolute path}}Copy the code

loader

When we load the CSS file, we find an error when webPack is packed, and the corresponding loader needs to parse it

Using CSS-loader to parse the CSS 1. Download

npm install css-loader -D
Copy the code

2. Use webpack. Config. Js

module.exprts = {
  module: {
    // Module configuration
    rules: [
      // Rule apply loader to module or modify parser
      {
        test: /\.css$/.// Regex matches
        use: ['css-loader'}]}}Copy the code

Packaging again found no errors, but the style is still not in effect. Because CSS-loader is only responsible for parsing loaded CSS, not inserted into the page. In this case, you need to use another loader, style-loader

Use the style – loader

  1. download
npm install style-loader -D
Copy the code
  1. use
module.exports = {
  module: {
    // Module configuration
    rules: [
      // Rule apply loader to module or modify parser
      {
        test: /\.css$/.// Regex matches
        use: ['style-loader'.'css-loader'] // 官网 : Loaders can be called by passing in multiple Loaders. They are applied from right to left (from last to first configured).}}}]Copy the code

In actual development, less, sass, and styles may be used to make webPack load and parse correctly. You only need to download the corresponding loader first and add the loader to the configuration file. * Pay attention to the configuration order, e.g. parse less: [‘style-loader’, ‘css-loader’, ‘less-loader’]