Vue注意事项之|vue多页面应用开发代码结构以及webpack配置
前段时间涉及到了多文件入口的vue应用,做下来比较有收获,也给革命一线的战友们分享一下自己的经验:
此次多入口vue应用的大概情况如图:


以module文件夹作为划分,将最终打包成一个的vue应用,根据路由切分为多个单独独立的功能块(这里的单独独立意味着每个功能块都是单独使用自己的vue实例、router等)。最终打包出来,是一个vue应用,但可根据上两图所示的路由区别,进入不同的模块应用,。在某些使用场景下方便用户操作。
应用场景比如:集成网站前台和后台管理的两个功能块,集成多个应用服务。
Vue文件篇
进入项目:
1.最外层目录里除index.html文件外,其余如main.js,App.vue之类的文件删去,如图:
2.进入src文件夹,发现正常该有的项目文件出现了~
这些文件按正常编写即可,然后多文件的藏身之处就在这里的modules文件夹里了。
3.进入modules文件夹,里面的文件夹就是各个功能块,也就是每个入口的文件夹。
随意进入一个文件夹后,你会发现每个都是单独的“洞天”,仿佛是一个完整的vue项目↓
不负众望,模块里面的文件写法也与普通项目无异,一个模块就是一个独立单元↓
这样,我们就把一个vue应用分成了多个模块,看起来,‘每个模块都像是一个单独的vue程序’,根据路由区分进入不同的模块。 大概的代码写法与架构如上所述,接下来还需要配置一下webpack.config文件
webpack配置篇
webpack.config文件只需要简单的对应配置一下,但是我在做的时候,网上找的很“揪心”,快从入门到放弃了?
好了,一起打开webpack.config吧,entry需要这样,只需关注entry
module.exports = {
externals: {
"echarts": "echarts",
"XLSX": "xlsx"
},
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js',
wxapp: './src/modules/wxapp/index.js',
wshop: './src/modules/wshop/index.js',
manage: './src/modules/manage/index.js',
activity: './src/modules/activity/index.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production' ?
config.build.assetsPublicPath :
config.dev.assetsPublicPath
},
看到,entry用入口文件路径对象了赋值,左侧key值分别是每个入门文件的名称,右侧value对应路径
然后依然在webpack.config文件中,plugins数组里,使用HtmlWebpackPlugin插件分别为每个入口文件配置,具体插件参数方法在文后链接给大家,主要要注意一点,chunks字段表示当前模块使用哪个入口js文件,值就是对应等于上面entry中的key值!
plugins: [
……
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
favicon: resolve('favicon.ico'),
title: 'vue-admin-template',
templateParameters: {
BASE_URL: config.build.assetsPublicPath + config.build.assetsSubDirectory,
},
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunks: ['app']
}), new HtmlWebpackPlugin({
filename: 'wxapp.html',
template: 'src/modules/wxapp/index.html',
inject: true,
favicon: resolve('favicon.ico'),
title: 'wxapp-template',
templateParameters: {
BASE_URL: config.build.assetsPublicPath + config.build.assetsSubDirectory,
},
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunks: ['wxapp']
}), new HtmlWebpackPlugin({
filename: 'wshop.html',
template: 'src/modules/wshop/index.html',
inject: true,
favicon: resolve('favicon.ico'),
title: 'wshop-template',
templateParameters: {
BASE_URL: config.build.assetsPublicPath + config.build.assetsSubDirectory,
},
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunks: ['wshop']
}),
new HtmlWebpackPlugin({
……
以上就为全部经验了,如果有需要补充或指证的地方欢迎修正,希望能帮助到需要的朋友.