Vue和ElementUI是目前非常流行的前端框架,webpack是常用的前端构建工具,能够输出MPA(多页应用)有助于提高前端页面的加载速度和SEO效果。下面是使用webpack输出MPA的步骤:
一、安装Webpack和一些必要的插件
npm install webpack webpack-cli html-webpack-plugin extract-text-webpack-plugin --save-dev
- webpack: 构建工具
- webpack-cli: 命令行工具
- html-webpack-plugin: 为每个页面生成HTML文件
- extract-text-webpack-plugin: 把CSS文件单独提取出来
二、配置Webpack
- 创建Webpack配置文件,例如webpack.config.js,配置entry、output等项:
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: './src/pages/index/index.js',
detail: './src/pages/detail/detail.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
chunkFilename: '[name].[chunkhash:5].js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.(css|scss)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin('[name].css'),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/pages/index/index.html',
chunks: ['vendors', 'index'],
inject: true
}),
new HtmlWebpackPlugin({
filename: 'detail.html',
template: './src/pages/detail/detail.html',
chunks: ['vendors', 'detail'],
inject: true
})
]
};
- 配置babel和vue-loader支持ES6和Vue单文件组件
.babelrc:
{
"presets": ["@babel/preset-env"]
}
以Vue单文件组件为例,配置vue-loader:
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
三、使用ElementUI
- 以ElementUI的Button组件为例,在Vue单文件组件中引入Button组件
<template>
<div>
<el-button type="primary">Primary</el-button>
<el-button>Default</el-button>
<el-button type="success">Success</el-button>
<el-button type="info">Info</el-button>
<el-button type="warning">Warning</el-button>
<el-button type="danger">Danger</el-button>
</div>
</template>
<script>
import 'element-ui/lib/theme-chalk/index.css'
// 导入Button组件
import { Button } from 'element-ui'
export default {
components: {
// 注册Button组件到当前Vue实例中
'el-button': Button
}
}
</script>
- 在webpack中引入ElementUI
在webpack.config.js中配置:
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.(css|scss)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /element-ui.src.*?js$/,
loader: 'babel-loader'
}
]
},
四、使用Webpack打包
- 运行webpack打包命令
webpack --config webpack.config.js
- 查看打包结果
打包完成后,在dist目录中生成打包后的文件,例如:
dist
├── detail.html
├── detail.js
├── index.html
├── index.js
├── vendors.js
├── index.css
└── detail.css
五、示例
这里提供两个示例:
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Vue+ElementUI项目使用webpack输出MPA的方法 - Python技术站