Loader

babel-loader

用来将ES6+语法转换成ES5
安装命令:
npm install babel-loader @babel/core @bable/preset-env

这个命令安装了三个npm包:
babel-loader 是Babel与Webpack协同工作的模块
@babel/core 是Babel的核心代码
@babel/preset-env 是Babel官方推荐的预置器

html-loader

可以加载html文件
安装:
npm install html-loader

配置:
rules:[
{
test:/.html$/,
use:’html-loader’
}
]

使用:
//header.html

file-loader

用于打包文件类型的资源,会生成并返回一个publicPath,即文件的路径
安装:
npm install file-loader

cache-loader

在一些性能开销较大的 loader 之前添加此 loader,以将结果缓存到磁盘里。

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.ext$/,
  6. use: [
  7. 'cache-loader',
  8. ...loaders
  9. ],
  10. include: path.resolve('src')
  11. }
  12. ]
  13. }
  14. }

⚠️ 请注意,保存和读取这些缓存文件会有一些时间开销,所以请只对性能开销较大的 loader 使用此 loader。

插件Plugins

BannerPlugin

为每个 chunk 文件头部添加 banner。

  1. new webpack.BannerPlugin(banner)
  2. // or
  3. new webpack.BannerPlugin(options)

CommonsChunkPlugin

将多个文件中的公共依赖提取出来。

  1. new webpack.optimize.CommonsChunkPlugin({
  2. name: "commons",
  3. // ( 公共chunk(commnons chunk) 的名称)
  4. filename: "commons.js",
  5. // ( 公共chunk 的文件名)
  6. // minChunks: 3,
  7. // (模块必须被3个 入口chunk 共享)
  8. // chunks: ["pageA", "pageB"],
  9. // (只使用这些 入口chunk)
  10. })

CopyWebpackPlugin

const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
module.exports = {
    context: path.join(__dirname, 'app'),
    devServer: {
        // This is required for older versions of webpack-dev-server
        // if you use absolute 'to' paths. The path should be an
        // absolute path to your build destination.
        outputPath: path.join(__dirname, 'build')
    },
    plugins: [
        new CopyWebpackPlugin([
            // {output}/file.txt
            { from: 'from/file.txt' },
            // equivalent
            'from/file.txt',
            // {output}/to/file.txt
            { from: 'from/file.txt', to: 'to/file.txt' },
            // {output}/to/directory/file.txt
            { from: 'from/file.txt', to: 'to/directory' },
            // Copy directory contents to {output}/
            { from: 'from/directory' },
            // Copy directory contents to {output}/to/directory/
            { from: 'from/directory', to: 'to/directory' },
            // Copy glob results to /absolute/path/
            { from: 'from/directory/**/*', to: '/absolute/path' },
            // Copy glob results (with dot files) to /absolute/path/
            {
                from: {
                    glob:'from/directory/**/*',
                    dot: true
                },
                to: '/absolute/path'
            },
            // Copy glob results, relative to context
            {
                context: 'from/directory',
                from: '**/*',
                to: '/absolute/path'
            },
            // {output}/file/without/extension
            {
                from: 'path/to/file.txt',
                to: 'file/without/extension',
                toType: 'file'
            },
            // {output}/directory/with/extension.ext/file.txt
            {
                from: 'path/to/file.txt',
                to: 'directory/with/extension.ext',
                toType: 'dir'
            }
        ], {
            ignore: [
                // Doesn't copy any files with a txt extension    
                '*.txt',
                // Doesn't copy any file, even if they start with a dot
                '**/*',
                // Doesn't copy any file, except if they start with a dot
                { glob: '**/*', dot: false }
            ],
            // By default, we only copy modified files during
            // a watch or webpack-dev-server build. Setting this
            // to `true` copies all files.
            copyUnmodified: true
        })
    ]
};

DefinePlugin

定义全局变量

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1",
  "typeof window": JSON.stringify("object")
})

DllPlugin

将不常变动的依赖单独打包,提高打包速度
webpack.vendor.config.js

new webpack.DllPlugin({
  context: __dirname,
  name: "[name]_[hash]",
  path: path.join(__dirname, "manifest.json"),
})

webpack.app.config.js

new webpack.DllReferencePlugin({
  context: __dirname,
  manifest: require("./manifest.json"),
  name: "./my-dll.js",
  scope: "xyz",
  sourceType: "commonjs2"
})

HtmlWebpackPlugin

该插件将为你生成一个 HTML5 文件, 其中包括使用 script 标签的 body 中的所有 webpack 包。 只需添加插件到你的 webpack 配置如下:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var webpackConfig = {
  entry: 'index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]
};

会自动包打包的bundle文件引入到HTML中。

IgnorePlugin

忽略不必要的打包,提高打包速度和减小打包体积。

new webpack.IgnorePlugin(requestRegExp, [contextRegExp])
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)

MinChunkSizePlugin

通过合并小于 minChunkSize 大小的 chunk,将 chunk 体积保持在指定大小限制以上,减少不必要的网络请求次数

new webpack.optimize.MinChunkSizePlugin({
  minChunkSize: 10000 // Minimum number of characters
})

PrefetchPlugin

预取出普通的模块请求(module request),可以让这些模块在他们被 import 或者是 require 之前就解析并且编译。使用这个预取插件可以提升性能。可以多试试在编译前记录时间(profile)来决定最佳的预取的节点。

new webpack.PrefetchPlugin([context], request)

ProvidePlugin

自动加载模块,而不必到处 importrequire

new webpack.ProvidePlugin({
  identifier: 'module1',
  // ...
})

or

new webpack.ProvidePlugin({
  identifier: ['module1', 'property1'],
  // ...
})
new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery'
})

optimization.splitChunks

分包

splitChunks: {
    chunks: "async",
    minSize: 30000,
    minChunks: 1,
    maxAsyncRequests: 5,
    maxInitialRequests: 3,
    automaticNameDelimiter: '~',
    name: true,
    cacheGroups: {
        vendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10
        },
    default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true
        }
    }
}

UglifyjsWebpackPlugin

文件压缩

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
  plugins: [
    new UglifyJsPlugin()
  ]
}

WatchIgnorePlugin

忽略监听指定文件的变化

new webpack.WatchIgnorePlugin(paths)

I18nWebpackPlugin

国际化插件

plugins: [
  ...
  new I18nPlugin(languageConfig, optionsObj)
],
  • optionsObj.functionName:默认值为 __, 你可以更改为其他函数名。
  • optionsObj.failOnMissing:默认值为 false,找不到映射文本(mapping text)时会给出一个警告信息,如果设置为 true,则会给出一个错误信息。
  • optionsObj.hideMessage:默认值为 false,将会显示警告/错误信息。如果设置为 true,警告/错误信息将会被隐藏。