webpack.config.js
var webpack = require("webpack");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var path = require("path");
module.exports={
entry: __dirname+"/main.js",
// {
// index:__dirname+"/index.js",
// main: __dirname+"/main.js"
// } ,
output:{
path:__dirname+"/dist",
filename:"[name].js"
},
module:{
rules:[
{
test:/\.vue$/,
loader:"vue-loader"
},
{
test:/\.js$/,
loader:"babel-loader",
options:{
"presets":[
"es2015"
]
}
},
{
test:/\.css$/,
use:[
"style-loader",
"css-loader"
]
},{
test:/\.html$/,
use:[
"html-loader"
]
},{
test:/\.png|.jpg|.gif$/,
loader:"url-loader"
}
]
},
devServer:{
//告诉服务器从哪里提供内容。这只有在您想要提供静态文件时才需要。例如图片??
contentBase:path.join(__dirname + 'dist'),
// --告诉服务器观看由devServer.contentBase选项提供的文件。文件更改将触发整个页面重新加载。
watchContentBase: true,
// --随所有内容启用gzip压缩
compress: true,
// 模块的热加载,必须结合 HotModuleReplacementPlugin使用
hot: true,
port: 9999,
host: "localhost",
inline:true,
//相当于gulp的middleware中间件拦截请求;
setup(app) {
app.get('/some/path', function(req, res) {
console.log(11)
res.json({ custom: 'response' });
});
},
// proxy:{
// // "/api": "http://localhost:3000/"
// "/api": "http://localhost:9000"
// // "/api": {
// // target: "http://localhost:3000",
// // pathRewrite: {"^/api" : ""},
// // secure: false
// // }
// }
},
plugins:[
new webpack.HotModuleReplacementPlugin(),
// new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: "commons",
// ( 公共chunk(commnons chunk) 的名称)
filename: "commons.js",
// ( 公共chunk 的文件名)
}),
new HtmlWebpackPlugin({
// filename: 'test.html',
template: "./index.html"
})
]
}
package.json
{
"name": "wlr",
"version": "1.0.0",
"description": "//生成文件npm run startr //启动服务,自动刷新npm run dev",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"webpack --config webpack.config.js",
"dev": "webpack-dev-server --config webpack.config.js --open"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"css-loader": "^0.28.7",
"html-loader": "^0.5.1",
"html-webpack-plugin": "^2.30.1",
"style-loader": "^0.19.0",
"url-loader": "^0.6.2",
"vue-loader": "^13.3.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.3"
}
}
遇见的问题
1.npm run dev 启动服务,报错
或者
报错原因:Webpack与webpack-dev-server版本不兼容导致。webpack是1.13.1,但webpack-dev-server是2.x以上的版本。
解决办法:将webpack-dev-server卸载掉:npm uninstall webpack-dev-server -g
然后安装1.15.0版本的webpack-dev-server,就可解决了此问题。:npm install webpack-dev-server@1.15.0 -g