1、安装:这里所有的安装都要注意版本,要和vue脚手架对应
cnpm install --save-dev webpack-dev-server
2、配置webpack.config.js文件的module.exports:
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
//entry指定入口文件,可以添加多个入口,然后生成多个出口
entry:{
home:path.resolve(__dirname,'./src/main.js')
},
//output指定出口文件,path必须是绝对路径,要先导入一个path,依赖与node
output:{
//node语法,__dirname获取当前文件的路径
path:path.resolve(__dirname,'dist'),
//这里的name是entry里的key,即home,这么写是方便生成多个出口时候的区分
filename:'[name].js'
//当用file-loader加载时,由于打包后图片在dist里,html读取的路径不一样,所以加一个publicpath
// publicPath:'dist/'
},
module:{
rules: [
{ //css-loader只负责将css文件解析加载,不负责渲染到html里,所以还需要一个sytle-loader
test: /\.css$/,
//webpack读取多个loader时,是从右往左读的,所以此loader顺序不能改变
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.less$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings,渲染到DOM
}, {
loader: "css-loader" // translates CSS into CommonJS,解析css
}, {
loader: "less-loader" // compiles Less to CSS,加载less编译成css
}]
},
{
test: /\.(png|jpg|gif)$/, //图片过滤
use: [
{
loader: 'url-loader',
options: {
//当加载的图片小于limit时候,会将图片编译成base64字符串形式
//当加载的图片大于limit时候,要用file-loader加载,但是要更改路径
limit: 8192,
//这里的【name】是指打包之前图片的名字,hash为哈希值,ext为扩展名,都为变量,固定写法
name:'img/[name].[hash:8].[ext]'
}
}
]
},
{ //大概从14开始,就需要插件来支持使用vue-loader,如果不安装,就改下package.json里的vue-loader版本,然后npm install
test: /\.vue$/,
use: ['vue-loader']
}
]
},
//此插件就是支撑vue-loader使用的
plugins: [
new VueLoaderPlugin(),
new webpack.BannerPlugin('最终版权归小二哥所有'),
//根据index.html生成dist里的index.html
new HtmlWebpackPlugin({
template:`index.html`
}),
new UglifyjsWebpackPlugin()
],
//添加resolve字段,指定vue编译版本为runtime-compiler
resolve:{
//alias别名
alias:{
'vue$':'vue/dist/vue.esm.js'
},
//指定哪些文件的后缀名省略
extensions: ['.js','.css','.vue']
},
//配置devServer本地服务器
devServer:{
//服务目录
contentBase:'./dist',
//是否实时刷新
inline:true
//也可以加个端口port:xxx
}
}
3、配置package.json:加入命令:"server": "webpack-dev-server --open",--open是自动打开浏览器的意思
{
"name": "meetwebpack",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode=development",
"build": "webpack --mode=production",
"server": "webpack-dev-server --open"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-preset-env": "^1.7.0",
"css-loader": "^3.5.3",
"file-loader": "^6.0.0",
"html-webpack-plugin": "^4.2.1",
"less": "^3.11.1",
"less-loader": "^6.0.0",
"style-loader": "^1.2.0",
"uglifyjs-webpack-plugin": "^2.2.0",
"url-loader": "^4.1.0",
"vue-loader": "^15.9.1",
"vue-template-compiler": "^2.6.11",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"vue": "^2.6.11"
}
}
4、执行命令运行:
npm run server
,当修改代码的时候就会实时刷新,开发就可以实时测试
5、开发本地服务测试完毕后,重新打包即可
npm run dev
网友评论