Vue构建的大多是SPA单页面应用,但有时候在实际项目中单页面应用并不一定符合业务需求
准备工作
利用vue-cli新建项目,再执行npm install命令安装所需依赖,之后需安装新依赖glob
1
| npm install --save-dev glob
|
修改webpack配置
需要改动的文件都在build文件夹下:
- util.js
- webpack.base.conf.js
- webpack.dev.conf.js
- webpack.prod.conf.js
utils.js 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
const glob = require('glob');
const page_path = path.join(__dirname, '../src/module');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
exports.entry = _ => { var entryFiles = glob.sync(page_path + '/*/*.js'); var map = {}; entryFiles.map(filePath => { let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.')); map[filename] = filePath; }); return map; }
exports.HtmlWebpackPlugin = _ => { var entryFiles = glob.sync(page_path + '/*/*.html'); var arr = []; entryFiles.map(filePath => { let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.')); let config = { template: filePath, filename: filename + '.html', inject: true, chunks: ['manifest', 'vendor', filename] } if (process.env.NODE_ENV === 'production') { config = merge(config, { minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunksSortMode: 'dependency' }) } arr.push(new HtmlWebpackPlugin(config)); }); return arr; }
|
webpack.base.conf.js 文件
原:
1 2 3
| entry: { app: './src/main.js' },
|
替换成
webpack.dev.conf.js 文件
注释掉:
并在
1
| plugins: [].concat(utils.HtmlWebpackPlugin())
|
webpack.prod.conf.js 文件
同上注释掉:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| plugins: [ ]
|
并在
1
| plugins: [].concat(utils.HtmlWebpackPlugin())
|
至此,webpack的配置就结束了。
文件结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| . ├── README.md ├── build │ ├── build.js │ ├── check-versions.js │ ├── logo.png │ ├── utils.js │ ├── vue-loader.conf.js │ ├── webpack.base.conf.js │ ├── webpack.dev.conf.js │ └── webpack.prod.conf.js ├── config │ ├── dev.env.js │ ├── index.js │ └── prod.env.js ├── package.json ├── src │ ├── assets │ │ └── logo.png │ ├── components │ │ ├── Hello.vue │ │ └── cell.vue │ └── module │ ├── cell │ │ ├── cell.html │ │ ├── cell.js │ │ └── cell.vue │ └── index │ ├── index.html │ ├── index.js │ ├── index.vue │ └── router │ └── index.js └── static
|
src为默认工程文件,其中的assets,components,module分别是静态资源文件、组件文件、页面文件。
页面文件中按照项目的模块分的文件夹,每个文件夹下分别有三个内容:vue文件,js文件和html文件。这三个文件的作用就相当于做spa单页面应用时,根目录的index.html页面模板,src文件下的main.js和app.vue的功能。
现在可以直接运行npm start试试看效果
相关代码:
参考地址: