安装

1
2
3
4
$ npm install -D webpack
$ npm install -D webpack-cli
# or use yarn
$ yarn add -D webpack
  • 如果需要在命令行运行,还需要全局安装

配置文件

  • 默认使用当前目录下的配置文件 webpack.config.js
  • 最基本的入口和输出配置是必须的
    1
    2
    3
    4
    5
    6
    7
    8
    9
    const path = require('path');

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

执行

主要参数

  • 指定运行模式mode,当然也可以在配置文件中指定,参数 node、development、production
  • 指定配置文件config,默认使用当前目录下的 webpack.config.js作为配置文件
  1. 将执行命令添加在package.json文件下的scripts: (推荐)

    1
    2
    3
    4
    "scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
    },
    1
    2
    $ npm run dev
    $ npm run build
  2. 在命令行执行:(需要全局安装)

    1
    $ webpack [--mode production] [--config webpack.config.js]
  3. 使用node.js执行

    1
    2
    3
    4
    5
    6
    7
    8
    const webpack = require('webpack'); //运行时(runtime)访问 webpack
    const configuration = require('./webpack.config.js');

    let compiler = webpack(configuration);

    compiler.run(function(err, stats) {
    err ? console.error(err) : console.log(stats);
    });

打印信息

  • 直接使用官方例子吧 0.0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    Hash: dabab1bac2b940c1462b
    Version: webpack 4.0.1
    Time: 323ms
    Built at: 2018-2-26 22:50:25
    Asset Size Chunks Chunk Names
    bundle.js 69.6 KiB 0 [emitted] main
    Entrypoint main = bundle.js
    [1] (webpack)/buildin/module.js 519 bytes {0} [built]
    [2] (webpack)/buildin/global.js 509 bytes {0} [built]
    [3] ./src/index.js 256 bytes {0} [built]
    + 1 hidden module

    WARNING in configuration(配置警告)
    // 这里的警告,是指没有设置打包模式 设置方式看上边执行
    The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.('mode' 选项还未设置。将 'mode' 选项设置为 'development' 或 'production',来启用环境默认值。)
  • Hash: 表示当前打包的Hash值,以区分每次打包,所以每次打包都会生成不同的Hash值
  • Version: 当前使用的webpack版本
  • Time: 本次打包花费时间
  • Built at:本次打包时刻
  • Asset: 打包生成的文件名
  • Size: 打包生成的文件大小
  • Chunks: 当前文件的chunk标识,用于区分不同的chunk (默认使用递增的chunkId标识,当然可以通过设置或者插件进行修改,对于chunk缓存优化有很大作用 参考其它文章)
  • [emitted] 表示生成
  • [immutable] 使用[contenthash]命名时出现 只要内容不变,生成的文件名(contenthash)就不会变
  • Chunk Names: 当前所属的chunk名称 (不同的chunk块,由不同的方式设置chunkName 参考其它文章)

其他说明

bundls.js: 是在output.filename中设置的
main: 是在entry中设置,(如果设置为字符串,则默认为main. 如果设置为对象,则使用key值,可以设置多个入口文件)

参考

webpack4 中文文档

备注

能写的都写了。。。