webpack打包多页面应用,先思考🤔完成多页面打包须要实现的目标:html
实现目标须要完成哪些任务:前端
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 配置完成,前三个任务完成node
接下来配置服务端对不一样入口访问时返回前端对应html页面webpack
本项目使用的 koa2 启动前端服务 此处 使用 koa2-history-api-fallback
完成了 路由 rewrite,此 npm 包是 connect-history-api-fallback
基于 koa2应用的实现git
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打包多页面应用已完成,主要用最简单例子讲述其中有哪些细节 优化处可本身实现:github
附上github: github.com/Jarryxin/mp…web
关于前端路由和后端路由的分析: www.cnblogs.com/songyao666/…npm