webpack多页面打包通用方案

发布于:2022-12-28 ⋅ 阅读:(580) ⋅ 点赞:(0)

1、多页面应用(MPA)概念

每一次页面跳转的时候,后台服务器都会返回一个新的index.html文档。这种类型的网站也就是多页网站,也叫做多页应用。

优势:1、页面之间解耦;2、对seo更加友好;

2、多页面打包基本思路:

每个页面对应一个entry,一个html-wenpack-plugin。

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

3、多页面打包通用方案

所谓通用方案就是增加页面不需要修改配置,动态获取entry和设置html-webpack-plugin数量。

利用glob.sync:glob - npm

  • entry: glob.sync(path.join(__dirname,'./src/*/index.js'));

这里需要约定每个模块的入口文件都为src下的某个文件夹中的index.js,如:(pageName: './src/pageName/index.js'),模板文件都为index.html。

对webpack.prod.js进行更改

const path = require('path');
const glob = require('glob');

const setMPA = () => {
    const entry = {};
    const HtmlWebpackPlugin = [];
    const entryFiles = glob.sync('./src/*/index.js');

    Object.keys(entryFiles).map((index)=>{
        const entryfile = entryFiles[index]
        const pageName = entryfile.match(/src\/(.*)\/index\.js/)
        console.log('pageName', pageName)

    })

    return {
        entry,
        HtmlWebpackPlugin
    }
}

setMPA()

 

通过输出看到pagename数组里的第二个位置的值是我们所需要的。

进一步完善逻辑

const path = require('path');
const glob = require('glob');

const setMPA = () => {
    const entry = {};
    const htmlWebpackPlugin = [];
    const entryFiles = glob.sync('./src/*/index.js');  // 获取到的entryFiles是一个数组
    // const entryFiles = glob.sync(path.join(__dirname,  './src/*/index.js'));

    Object.keys(entryFiles).map((index)=>{

        const entryfile = entryFiles[index]  // 获取到数组中的每一项
        const file = entryfile.match(/src\/(.*)\/index\.js/)  //
        const pageName = file && file[1]
        // console.log('pageName', pageName)

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

    return {
        entry,
        htmlWebpackPlugin
    }
}

const {entry, htmlWebpackPlugin} = setMPA()

然后还要将输出的entry替换原来的

entry: entry,

htmlWebpackPlugin替换原来的

    plugins:[
        new MiniCssExtractPlugin({
            filename: '[name]_[contenthash:8].css'
        }),
        new CleanWebpackPlugin(),

        new HTMLInlineCSSWebpackPlugin()
    ].concat(htmlWebpackPlugin),  // 接在数组上

这样就可以实现新增页面也不用修改webpack配置,直接打包了。

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到