webpack 多页面应用打包

说白了就是使用正则,把对应的 entry 匹配出来,然后对应生成对应的 htmlWebpackPlugins,到最后丢到插件里面。

多页面应用(MPA)概念

每一次页面跳转的时候,后台服务器都会返回一个新的 html 文档。

这种类型的⽹网站也就是多⻚页⽹网站,也叫做多页面应用。

多⻚页⾯面打包基本思路路

每个⻚页⾯面对应⼀一个 entry,⼀一个 html-webpack-plugin

缺点:每次新增或删除⻚页⾯面需要改 webpack 配置

module.exports = {
  entry: {
    index: './src/index.js',
    search: './src/search.js ‘
  }
}

多⻚页⾯面打包通⽤用⽅方案

动态获取 entry 和设置 html-webpack-plugin 数量量

利利⽤用 glob.sync

npm install glob -S
entry: glob.sync(path.join(__dirname, './src/*/index.js')),
module.exports = {
	entry: {
		index: './src/index/index.js',
		search: './src/search/index.js ‘
		}
	}

最后的webpack.config.js其实是长这个样子

'use strict';

const glob = require('glob');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HTMLInlineCSSWebpackPlugin = require('html-inline-css-webpack-plugin').default;
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const setMPA = () => {
    const entry = {};
    const htmlWebpackPlugins = [];
    const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'));

    Object.keys(entryFiles)
        .map((index) => {
            const entryFile = entryFiles[index];
            const match = entryFile.match(/src\/(.*)\/index\.js/);
            const pageName = match && match[1];

            entry[pageName] = entryFile;
            htmlWebpackPlugins.push(
                new HtmlWebpackPlugin({
                    inlineSource: '.css$',
                    template: path.join(__dirname, `src/${pageName}/index.html`),
                    filename: `${pageName}.html`,
                    chunks: ['vendors', pageName],
                    inject: true,
                    minify: {
                        html5: true,
                        collapseWhitespace: true,
                        preserveLineBreaks: false,
                        minifyCSS: true,
                        minifyJS: true,
                        removeComments: false
                    }
                })
            );
        });

    return {
        entry,
        htmlWebpackPlugins
    }
}

const { entry, htmlWebpackPlugins } = setMPA();

module.exports = {
    entry: entry,
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name]_[chunkhash:8].js'
    },
    mode: 'production',
    module: {
        rules: [
            {
                test: /.html$/,
                use: 'inline-html-loader'
            },
            {
                test: /.js$/,
                use: [
                    'babel-loader',
                ]
            },
            {
                test: /.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            },
            {
                test: /.less$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    {
                        loader: 'px2rem-loader',
                        options: {
                            remUnit: 75,
                            remPrecision: 8
                        }
                    },
                    'less-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: () => [
                                require('autoprefixer')({
                                    browsers: ['last 2 version', '>1%', 'ios 7']
                                })
                            ]
                        }
                    }
                ]
            },
            {
                test: /.(png|jpg|gif|jpeg)$/,
                use: [
                    {
                        loader: 'inline-file-loader',
                        options: {
                            name: '[name]_[hash:8].[ext]'
                        }
                    }
                ]
            },
            {
                test: /.(woff|woff2|eot|ttf|otf)$/,
                use: [
                    {
                        loader: 'inline-file-loader',
                        options: {
                            name: '[name]_[hash:8][ext]'
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name]_[contenthash:8].css'
        }),
        new OptimizeCSSAssetsPlugin({
            assetNameRegExp: /\.css$/g,
            cssProcessor: require('cssnano')
        }),
        new CleanWebpackPlugin(),  
    ].concat(htmlWebpackPlugins).concat(new HTMLInlineCSSWebpackPlugin()),
    stats: 'errors-only'
};
posted @ 2020-09-15 10:24  jaiodfjiaodf  阅读(542)  评论(0编辑  收藏  举报