webpack 高级配置

目录

1. 配置多入口

1.1 entry 配置

1.2 生产环境 output 配置

1.3 plugins 入口 html 文件配置

2. 抽离 CSS 文件

2.1 引入 mini-css-extract-plugin

2.2 使用 MiniCssExtractPlugin.loader

2.3 抽离 CSS 文件 

2.4 压缩 CSS 文件

3. 抽离公共代码和第三方代码

3.1 配置 optimization 下的 splitChunks

3.2 配置 HtmlWebpackPlugin 插件

4. 懒加载

5. 处理 JSX

5.1 安装 babel/preset-react

5.2 配置 .babelrc

5.3 配置 babel-loader 解析 js 语法

6. 处理 Vue

6.1 安装 vue-loader

6.2 配置 vue-loader


1. 配置多入口

1.1 entry 配置

// webpack.common.js

entry: {
        index: path.join(srcPath, 'index.js'),
        other: path.join(srcPath, 'other.js')
    },

1.2 生产环境 output 配置

  • 打包代码时,加上 hash 戳
  • name 即多入口 entry 的 key
  • CleanWebpackPlugin 每次打包前,清理之前打包内容
// webpack.prod.js

output: {
        // filename: 'bundle.[contentHash:8].js',  // 打包代码时,加上 hash 戳
        filename: '[name].[contentHash:8].js', // name 即多入口时 entry 的 key
        path: distPath,
    },
plugins: [
        new CleanWebpackPlugin(), // 会默认清空 output.path 文件夹
        new webpack.DefinePlugin({
            // window.ENV = 'production'
            ENV: JSON.stringify('production')
        })
    ]

1.3 plugins 入口 html 文件配置

  • 生成多个 HtmlWebpackPlugin 实例
  • chunks 表示该页面要引用哪些 chunk (即 entry 的 index 和 other),默认全部引用
// webpack.common.js

plugins: [
        // new HtmlWebpackPlugin({
        //     template: path.join(srcPath, 'index.html'),
        //     filename: 'index.html'
        // })

        // 多入口 - 生成 index.html
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'index.html'),
            filename: 'index.html',
            // chunks 表示该页面要引用哪些 chunk (即上面的 index 和 other),默认全部引用
            chunks: ['index']  // 只引用 index.js
        }),
        // 多入口 - 生成 other.html
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'other.html'),
            filename: 'other.html',
            chunks: ['other']  // 只引用 other.js
        })
    ]

2. 抽离 CSS 文件

  • 开发环境下使用 style-loader 通过