Webpack 4.x搭建Vue腳手架踩坑記錄
阿新 • • 發佈:2018-12-20
博主最近在自己搭建一個vue的腳手架,因為感覺之前直接使用官方vue-cli之後,對於Webpack的使用不太熟悉,加上vue-cli3.0版本把webpack.config.js配置檔案置換成自己的配置檔案了之後,對於Webpack的使用就更加不熟練了。這裡總結一下搭建時遇到的坑,謹防再犯錯吧。
版本不相容問題
博主使用的webpack版本號為 4.25.1,對於npm install預設安裝的一些loader等都有不相容的可能,如果同為4.x版本的可以按以下版本號為參考進行安裝,避免不必要的問題。
"dependencies": { "vue": "^2.5.17" }, "devDependencies": { "babel": "^6.23.0", "babel-core": "^6.26.3", "babel-loader": "^7.1.4", "babel-plugin-transform-runtime": "^6.23.0", "babel-preset-es2015": "^6.24.1", "babel-runtime": "^6.26.0", "css-loader": "^1.0.1", "file-loader": "^2.0.0", "mini-css-extract-plugin": "^0.4.4", "style-loader": "^0.23.1", "url-loader": "^1.1.2", "vue-hot-reload-api": "^2.3.1", "vue-loader": "^15.4.2", "vue-router": "^3.0.1", "vue-style-loader": "^4.1.2", "vue-template-compiler": "^2.5.17", "webpack": "^4.25.1", "webpack-cli": "^3.1.2", "webpack-dev-server": "^3.1.10" }
css分離
在3.0以及之前版本,css分離通常使用extract-text-webpack-plugin外掛,但在4.0版本會報出版本不匹配的錯誤,這是因為4.x版本的webpack捨棄了該外掛轉而使用mini-css-extract-plugin外掛,刪除原有的extract-text-webpack-plugin外掛,重新安裝mini-css-extract-plugin外掛即可解決問題。 具體配置如下
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const path = require('path'); var config={ //入口檔案的配置項 entry:'./src/main.js', //出口檔案的配置項 output:{ //輸出的路徑,用了Node語法 path:path.resolve(__dirname,'dist'), publicPath:"/dist/", //輸出的檔名稱 filename:'build.js' }, //模組:例如解讀CSS,圖片如何轉換,壓縮 module:{ rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, "css-loader" ] } ] }, //外掛,用於生產模版和各項功能 plugins:[ new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name].css", chunkFilename: "[id].css" }) ], //配置webpack開發服務功能 devServer:{} }; module.exports=config;
接下來是babel的版本問題
"babel-loader": "^7.1.4",
8.0以上版本可能也會有不相容的問題。
webpack出入口檔案的路徑問題
無論哪個版本的webpack,出入口檔案路徑都要注意,入口檔案使用相對路徑而出口檔案只能使用絕對路徑。
//入口檔案的配置項 entry:'./src/main.js', //出口檔案的配置項 output:{ //輸出的路徑,用了Node語法 path:path.resolve(__dirname,'dist'), publicPath:"/dist/", //輸出的檔名稱 filename:'build.js' },
另外注意 publicPath:"/dist/",設定,當你使用 npm run serve/npm run dev需要設定該虛擬路徑目錄儲存才能正常使用。