webpack多页面配置

2018-09-29  本文已影响0人  visitor009
$_> npm i -D webpack webpack-merge html-webpack-plugin clean-webpack-plugin mini-css-extract-plugin css-loader
// webpack.config.js
let path = require('path')
let webpack = require('webpack')

let merge = require('webpack-merge')
let HtmlWebpackPlugin = require('html-webpack-plugin')
let CleanWebpackPlugin = require('clean-webpack-plugin')
let MiniCssExtractPlugin = require("mini-css-extract-plugin");

// 基础配置
let baseConfig = {
    entry: {
        'vue': ['vue']
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].[chunkhash].js'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                    options: {
                        publicPath: '../css/'
                      }
                },"css-loader"]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css"
        }),
        new CleanWebpackPlugin(path.resolve(__dirname, 'dist')),

    ],
    optimization: { // js提取公共代码
        splitChunks: {
          chunks: 'async',
          minSize: 30000,
          maxSize: 0,
          minChunks: 1,
          maxAsyncRequests: 5,
          maxInitialRequests: 3,
          automaticNameDelimiter: '~',
          name: true,
          cacheGroups: {
            common: {
              name: 'vue',
              chunks: 'initial',
              priority: 2,
              minChunks: 2,
            },
          }
        }
      }
}

// 配置页面函数
let generatePage = function ({
    title = '',
    entry = '',
    template = './src/index.html',
    name = '',
    chunks = []
} = {}) {
    return {
        entry,
        plugins: [
            new HtmlWebpackPlugin({
                chunks,
                template,
                title,
                filename: name + '.html'
            })
        ]
    }
}
// 配置页面
let pages = [
    generatePage({
        title: 'page A',
        entry: {
            'a': './src/pages/a'
        },
        name: 'a',
        chunks: ['vue', 'a']
    }),
    generatePage({
        title: 'page B',
        entry: {
            'b': './src/pages/b'
        },
        name: 'b',
        chunks: ['vue', 'b']
    }),
    generatePage({
        title: 'page C',
        entry: {
            'c': './src/pages/c'
        },
        name: 'c',
        chunks: ['vue', 'c']
    })
]
// 通过merge来合成一个配置
module.exports = pages.map(page => merge(baseConfig, page))

// 模板 index.html
 <title><%= htmlWebpackPlugin.options.title %></title>
目录.JPG
上一篇下一篇

猜你喜欢

热点阅读