webpack如何打包多页面应用(mpa)

1,218 阅读2分钟

前言

webpack打包多页面应用,先思考🤔完成多页面打包需要实现的目标:

  • 多入口访问,访问/index1时显示/index1.html,访问/index2时显示/index2.html
  • 单入口访问,只用完成访问/时显示/index.html

实现目标需要完成哪些任务:

  • 入口文件需要写入两个
  • 出口文件根据入口文件名输出
  • 生成html模板插件(HtmlWebpackPlugin)需运行两次,为每个入口文件生成包含对应js文件的html
  • 若前端路由使用的 browserHistory,则需要在服务端处理访问 /index1时 返回 /index1.html的对应问题

实现

Talk is cheap. Show me your code.

const webpackConfig = {
    // ... other config
    entry: {
        index1: [./src/index1.js],
        index2: [./src/index2.js],
    },
    output: {
        path: path.resolve(__dirname, '../build'),
        filename: '[name]-[hash:4].js',
        chunkFilename: '[name]-[hash:4].chunk.js',
        publicPath: '/',
    },
    optimization: {
        runtimeChunk: false,
        splitChunks: {
            cacheGroups: {
                vendors: {
                  test: /[\\/]node_modules[\\/]/,
                  name: 'vendor',
                  chunks: 'all',
                  minChunks: 2,
                },
          },
        },
    },
    // ... loader ...
    plugins: [
        // ... other plugins
        new HtmlWebpackPlugin({
            inject: true,
            filename: 'index1.html', // 输出的html名称,默认为 index.html
            template: path.resolve(__dirname, '../public/template.html'),
            // Allows to control how chunks should be sorted before they are included to the HTML. Allowed values are 'none' \| 'auto' \| 'dependency' \| 'manual' \| {Function}
            // 简单解释: 控制多个 chunks 的在html注入的顺序
            chunksSortMode: 'dependency',
            chunks: ['index1', 'vendor'], // 该 vendor 文件是使用 splitChunks打包出的公共 node_modules js文件,如果没用则不用加
        }),
        new HtmlWebpackPlugin({
            inject: true,
            filename: 'index2.html',
            template: path.resolve(__dirname, '../public/template.html'), //模板可用不同的
            chunksSortMode: 'dependency',
            chunks: ['index2', 'vendor'],
        })
    ]
}

至此 webpack 配置完成,前三个任务完成

接下来配置服务端对不同入口访问时返回前端对应html页面

本项目使用的 koa2 启动前端服务 此处 使用 koa2-history-api-fallback 完成了 路由 rewrite,此 npm 包是 connect-history-api-fallback 基于 koa2应用的实现

app.use(history({
    rewrites: [{
        from: /^\/[a-zA-Z0-9/]+$/, // 匹配 /index1/view/login/dengdeng
        to: function(context) {
            const { pathname } = context.parsedUrl
            const page = pathname.match(/^\/[^/]*/[0].substr(1))
            return `/${page}.html` // 返回 /index1.html 有前端路由决定渲染
        }
    }]
}))

webpack打包多页面应用已完成,主要用最简单例子讲述其中有哪些细节 优化处可自己实现:

  • 使用读文件包读取 有哪些入口文件,然后遍历文件名到 entry 处
  • HtmlWebpackPlugin 处可以循环有哪些入口文件遍历出渲染哪些页面 💫

附上github: github.com/Jarryxin/mp…


关于前端路由和后端路由的分析: www.cnblogs.com/songyao666/…