webpack4.0配置如下
const path=require("path")
const HtmlWebpackPlugin=require("html-webpack-plugin")//用于把HTML頁面放入記憶體
const vueload=require("vue-loader/lib/plugin")
const WorkboxWebpackPlugin=require("workbox-webpack-plugin")
const htmlplugin=new HtmlWebpackPlugin({
template:path.join(__dirname,'./src/index.html'),//源頭檔案
filename:"index.html"//生成首頁的檔案名稱
})
module.exports={//webpack基于node建構的
mode:"production",
entry: {
index: './src/index.js'
},
//webbox
output: {
filename: 'js/main.[hash:8].js',//通過熱加載輸出script檔案挂載在目錄與index.HTML一樣
path: path.resolve(__dirname, 'dist')
},
//production 提供了約定大于配置 約定打封包件是src/index ->dist/main
plugins:[
htmlplugin,
new vueload(),
new WorkboxWebpackPlugin.GenerateSW({
clientsClaim:true,//快速啟動
skipWaiting:true//删除舊的 生成service work
})
],
module: {//是以第三方子產品的配置規則
rules: [
// { test:/.vue$/,use:[{loader:"vue-loader"}]},
{test:/\.vue$/,use:"vue-loader"},
{
test: /\.js$/,
loader: 'babel-loader',
exclude:/node_modules/
}
]
}
}
package.json
建議複制配置
```javascript
{
"name": "shop",
"version": "1.0.0",
"description": "A Vue.js project",
"author": "liuyong-byte <[email protected]>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --open --inline --progress --config webpack.config.js",
"build":"webpack --config webpack.config.js"
},
"dependencies": {
"vue": "^2.5.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"html-webpack-plugin": "^4.3.0",
"vue-loader": "^15.9.2",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0",
"workbox-webpack-plugin": "^5.1.3"
}
}
.babelrc配置
{
"presets": [["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],"stage-0"],
"plugins": ["transform-runtime"]
}
index.js
如果你使用了eslint 會報錯
需要砸package配置json中
eslintConfig:{
“env”:{“browser”:true},//需要支援node全局就寫node為true
}
if('serviceWorker' in navigator){
window.addEventListener("load",()=>{
navigator.serviceWorker.register('/service-worker.js').then(()=>{
console.log("成功");
}).catch(()=>{
console.log("失敗")
})
})
}
然後如果你之前使用了webpack-dev-server 那麼可以直接跑起來一點問題沒有
但是 如果你想打包出去build webpack 自己獨立的用nodejs 配置web架構跑起來會報錯
如果有朋友解決了 請告訴學生黨一下
是以推薦安裝一個npm install serve -g 全局安裝
然後 serve -s build(這是打包的檔案所在檔案夾)運作
就會出現預設的localhost:5000然後運作 一點錯都沒有
然後打開浏覽器 F12 檢視
然後關掉網絡
重新整理頁面