Webpack


基础概念

treeshaking

treeshaking 基于 ES module,可以通过 sideEffect 配置

usedExports 设为 true

优化

rollup-plugin-visualizer是一个打包体积分析插件,对应webpack中的webpack-bundle-analyzer

Webpack Monitor


  • Babel
  • ESLint

webpack 是什么?

webpack 把所有资源(asset,不管是html,css,jpg)都当作模块,webpack 只理解 JavaScript。

准备

webpack 是基于 Node 环境的,所以我们要先安装 Node 环境(就好比 Java 需要 JRE),安装 Node 简易使用 nvm(一个 Node 安装以及版本管理工具)。

基础

npm init -y
npm install webpack webpack-cli webpack-dev-server --save-dev
npm install html-webpack-plugin --save-dev
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'
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Test',
      template: './src/index.html'
    })
  ],
  devServer: {
    contentBase: './dist',
    hot: true
  },
  output: {
    filename: '[name].[chunkhash].js',
    path: path.resolve(__dirname, 'dist')
  }
};

修改 package.json

{
  ...
  "scripts": {
    "build": "webpack",
    "start": "webpack-dev-server --open"
  },
  ...
}

手动建立

/src/index.js
/src/index.html

使用 babel

npm install babel-loader babel-core babel-preset-env webpack
module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    }
  ]
}

1. 开始

安装

进入项目目录 demo

先初始化npm(其实先初始化或先安装都可以)

npm init

安装webpack

npm install --save-dev webpack  # 推荐本地安装
npm install --global webpack
配置

新建程序源码目录 src,将入口文件 index.js 文件放在 src 目录。

  1. index.js 只是一个测试文件,我们随便写一些代码:
console.log('Hello world!');
  1. 根目录新建一个配置文件:webpack.config.js
const path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};
  • 这个文件指定了基本的entry和output,稍后我们会解释这个文件中的配置项。
打包编译
./node_modules/.bin/webpack

2. 使用依赖

我们以jQuery为例

npm install --save jquery

在 index.js 文件中 import

import $ from 'jquery';

$('body').html('Hello world!');

3. 更方便的运行

运行 ./node_modules/.bin/webpack 太复杂了。

新建 package.json

{
  "scripts": {
    "build": "webpack"
  }
}

这样就可以直接运行 npm run build

4. 加载css 、图片、字体

加载css需要添加 style-loader 和 css-loader:

npm install --save-dev style-loader css-loader
  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'
+         ]
+       }
+     ]
+   }
  };

这样你就可以直接在 index.js 中引入 css。 注意:引用路径要加上 ./

import './style.css';

问了节省css加载时间,可以使用css分离:ExtractTextWebpackPlugin

同理,使用file-loader来加载图片或字体,并且可以使用 image-webpack-loader 和 url-loader 来压缩和优化图片。

npm install --save-dev file-loader

5. 自动将bundle文件插入到html页面

需要使用webpack插件 HtmlWebpackPlugin

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({
        template:path.join(__dirname, 'src/index.ejs'), // 如果需要一个模板
        title: '生成HTML的标题'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
};

每次都生成新的bundle,需要清理dist文件夹

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')
    }
  };

6. 实时刷新

"watch": "webpack --watch",

使用webpack-dev-server

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

修改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'
    },
    devtool: 'inline-source-map',
+   devServer: {
+     contentBase: './dist'
+   },
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Development'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

修改package.json的script

  {
    "name": "development",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "watch": "webpack --progress --watch",
+     "start": "webpack-dev-server --open",
      "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "clean-webpack-plugin": "^0.1.16",
      "css-loader": "^0.28.4",
      "csv-loader": "^2.1.1",
      "file-loader": "^0.11.2",
      "html-webpack-plugin": "^2.29.0",
      "style-loader": "^0.18.2",
      "webpack": "^3.0.0",
      "xml-loader": "^1.2.1"
    }
  }

最后

npm start

7. CSS分离

# 对于 webpack 3
npm install --save-dev extract-text-webpack-plugin

用法

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

7. CSS背景图使用相对路径


      {
        test:/\.(png|svg|jpg|gif)$/,
        use:[
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets/img/',
              // outputPath: path.resolve(__dirname, 'dist/assets/img/'),
              name: '[name].[ext]?[hash]',
              // publicPath:'/',
              useRelativePath:true  // 相对路径是相对于css,取决于你在css的url()里面怎么写,配合outputPath比较好
            }
          }
        ]
      }

自带uglify?

https://github.com/jantimon/html-webpack-plugin https://github.com/jaketrent/html-webpack-template

更新时间:2025-03-13 13:14:39