webpack之多页面打包通用方案

多页面应用(MPA)

概念:

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

优势:

  1. 页面之间的解耦
  2. 更利于SEO

多页面打包基本思路:

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

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

多页面应用通用打包方案

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

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

上面我们简单的理了一下思路,那么下面我们就开始操作:

1.安装依赖

cnpm i glob html-webpack-plugin -D

2.src下新建文件,目录如下图:

meta.html是我用来资源内联的,可以忽略

3.package.json中配置命令(个人习惯)

4.webpack.config.js中配置:

"use strict";

const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const glob=require('glob');

const setMPA = () => {
    const entry = {};
    const htmlWebpackPlugins = [];

    // glob.sync同步获取匹配目录下的文件
    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({
                    template: path.join(__dirname, `src/${pageName}/index.html`),
                    filename: `${pageName}.html`,
                    chunks: ['vendors', pageName],
                })
            )

        })  
    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:{
    },
    plugins:[
        
    ].concat(htmlWebpackPlugins)
}

5.npm run start打包。

最后我们看一下效果:

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值