vue相关webpack配置
一.安装webpack
创建文件夹,进入文件夹执行
//初始化项目
npm i
//安装webpack
npm install --save-dev webpack webpack-cli
在当前目录创建webpack.config.js文件
const path = require('path')
module.exports = {
entry: 'main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {...}
}
二.安装相关loader
1.安装css相关
npm install --save-dev css-loader style-loader
//webpack.config.js中
module.export = {
module: {
rules:[
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
}
2.安装图片相关
npm install --save-dev file-loader
//webpack.config.js中
module.exports = {
module: {
rules: [
{
test: /\.(jpg|png|gif|svg)$,
use: ['file-loader']
}
]
}
}
//另一种
npm install --save-dev url-loader file-loader
//webpack.config.js中
module.exports = {
module: {
rules: [
{
test: /\.(jpg|png|gif|svg)$,
use: {
loader: 'url-loader',
options: {
limit: 8962,
//当图片大小小于8962k时,图片转化为base64格式,
}
}
}
]
}
}
3.安装babel(es7es6转化为es5)
npm install --save-dev babel-loader @babel/core @babel-preset-env
//webpack.config.js中
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
}
4.安装vue相关文件loader
npm install vue -S
//若是要指定vue用runtime-compiler版本,则需要在webpack中指定
module.exports ={
...
module:{...}
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
}
编译识别 .vue 文件,则安装以下
npm install --save-dev vue-loader vue-template-compiler
webpack.config.js中
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
module: {
rules: [
{
test: /\.vue$,
use: 'vue-loader'
}
]
},
//若是安装vue-loader在版本14以下,则不用安装该插件
plugins: {
new VueLoaderPlugin()
}
}
三.安装html-webpack-plugin
npm install --save-dev html-webpack-plugin
webpack.config.js中
const HtmlWebpackPlugin = require('html-webpack-plugin')
const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: 'index.html'
})
]
}
四. 使用webpack-dev-server
npm install --save-dev webpack-dev-server
devServer: {
contentBase: './dist',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
},
T h e p u b l i c P a t h w i l l b e u s e d w i t h i n o u r s e r v e r s c r i p t a s w e l l i n o r d e r t o m a k e s u r e f i l e s a r e s e r v e d c o r r e c t l y o n h t t p : / / l o c a l h o s t : 3000. W e ′ l l s p e c i f y t h e p o r t n u m b e r l a t e r . T h e n e x t s t e p i s s e t t i n g u p o u r c u s t o m e x p r e s s s e r v e r : The publicPath will be used within our server script as well in order to make sure files are served correctly on http://localhost:3000. We'll specify the port number later. The next step is setting up our custom express server: ThepublicPathwillbeusedwithinourserverscriptaswellinordertomakesurefilesareservedcorrectlyonhttp://localhost:3000.We′llspecifytheportnumberlater.Thenextstepissettingupourcustomexpressserver: