babel7 後來的版本捨棄了之前的 babel-- 的命名方式,改爲了 @babel/-
修改依賴和 .babelrc 文件後就能正常啓動項目了,文檔。
參考 http://www.javashuo.com/article/p-agbqdssa-dh.html,
https://www.jianshu.com/p/e21d19875fbbphp
緣由是clean-webpack-plugin插件更新版本後,new cleanWebpackPlugin(),裏只能傳一個對象參數了,配置地址https://github.com/johnagan/clean-webpack-plugin#options-and-defaults-optionalcss
趁工做之餘從零構建了一個webpack4.x多頁面應用程序。過程當中也遇到一些坑,就記錄下來了。html
項目的運行主要圍繞的就是這幾大塊 node
首先看一下構建後目錄
├── build
│ ├── webpack.base.conf.js
│ ├── webpack.dev.conf.js
│ ├── webpack.prod.conf.js
│ ├── webpack.rules.conf.js
├── src
│ ├── css
│ ├── js
│ ├── images
│ ├── assets
│ ├── pages
│ │ ├── index
│ │ │ ├── index.html
│ │ │ ├── index.js
│ │ │ └── index.scss
│ │ ├── login
│ │ │ ├── index.html
│ │ │ ├── index.js
│ │ │ └── index.scssjquery
修改 webpack.base.conf.js代碼 entry: { // 多入口文件 index: ['./src/pages/index/index.js',], login: './src/pages/login/index.js', },
npm install webpack-dev-server --save-dev //修改 webpack.dev.conf.js代碼 devServer: { contentBase: path.join(__dirname, "../dist"), publicPath:'/', host: "127.0.0.1", port: "8089", overlay: true, // 瀏覽器頁面上顯示錯誤 // open: true, // 開啓自動打開瀏覽器 // stats: "errors-only", //stats: "errors-only"表示只打印錯誤: hot: true // 開啓熱更新 }, //修改package.json scripts: { "dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.dev.conf.js", "build": "cross-env NODE_ENV=production webpack --config build/webpack.prod.conf.js", "server": "live-server ./ --port=8888" },
{ test: /\.(css|scss|sass)$/, // 不分離的寫法 // use: ["style-loader", "css-loader",sass-loader"] // 使用postcss不分離的寫法 // use: ["style-loader", "css-loader", sass-loader","postcss-loader"] // 此處爲分離css的寫法 /*use: extractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader", "sass-loader"], // css中的基礎路徑 publicPath: "../" })*/ // 此處爲使用postcss分離css的寫法 use: extractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader", "sass-loader", "postcss-loader"], // css中的基礎路徑 publicPath: "../" }) }, { test: /\.js$/, use: ["babel-loader"], // 不檢查node_modules下的js文件 exclude: "/node_modules/" }, { test: /\.(png|jpg|gif)$/, use: [{ // 須要下載file-loader和url-loader loader: "url-loader", options: { limit: 5 * 1024,//小於這個時將會已base64位圖片打包處理 // 圖片文件輸出的文件夾 outputPath: "images" } }] }
npm install extract-text-webpack-plugin --save-dev //這個插件在webpack4.x 運行時會有點問題,後面會提到 //修改 webpack.base.conf.js代碼 // 分離css插件參數爲提取出去的路徑 new extractTextPlugin({ filename: 'css/[name].[hash:8].min.css', }),
//屬性自動加前綴 npm install postcss-loader --save-dev //在根目錄新建postcss.config.js module.exports = { plugins: [ require('autoprefixer')//自動添加css前綴 ] }; //loader里加入postcss { test: /\.(css|scss|sass)$/, // 此處爲使用postcss分離css的寫法 use: extractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader", "sass-loader", "postcss-loader"], // css中的基礎路徑 publicPath: "../" }) } //修改package.json 加入css要兼容瀏覽器版本的代碼 "browserslist": [ "defaults", "not ie < 11", "last 2 versions", "> 1%", "iOS 7", "last 3 iOS versions" ] //消除冗餘css代碼 使用glob模塊去匹配文件因此還要安裝glob模塊 npm install purifycss-webpack --save-dev new purifyCssWebpack({ paths: glob.sync(path.join(__dirname, "../src/pages/*/*.html")) }), //壓縮css npm install optimize-css-assets-webpack-plugin --save-dev //壓縮css //修改 webpack.prod.conf.js代碼 new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }),
npm install clean-webpack-plugin --save-dev //修改 webpack.prod.conf.js代碼 //刪除dist目錄 new cleanWebpackPlugin(['dist'], { root: path.resolve(__dirname, '../'), //根目錄 // verbose Write logs to console. verbose: true, //開啓在控制檯輸出信息 // dry Use boolean "true" to test/emulate delete. (will not remove files). // Default: false - remove files dry: false, }),
npm install uglifyjs-webpack-plugin --save-dev //修改 webpack.prod.conf.js代碼 //上線壓縮 去除console等信息webpack4.x以後去除了webpack.optimize.UglifyJsPlugin //https://github.com/mishoo/UglifyJS2/tree/harmony#compress-options new UglifyJSPlugin({ uglifyOptions: { compress: { warnings: false, drop_debugger: false, drop_console: true } } }),
// webpack4裏面移除了commonChunksPulgin插件,放在了config.optimization裏面,提取js, vendor名字可改 optimization: { splitChunks: { cacheGroups: { vendor: { // test: /\.js$/, test: /[\\/]node_modules[\\/]/, chunks: "initial", //表示顯示塊的範圍,有三個可選值:initial(初始塊)、async(按需加載塊)、all(所有塊),默認爲all; name: "vendor", //拆分出來塊的名字(Chunk Names),默認由塊名和hash值自動生成; enforce: true, } } } }, //項目裏配置了自動提取node_modules裏用到的模塊如jquery,也能夠在原模板裏面經過第三方cdn引入,又是另外一種配置了。在 webpack.base.conf.js利配置externals後webpack就不會去打包配置模塊 externals: { 'jquery': 'window.jQuery' }, //externals就是webpack能夠不處理應用的某些依賴庫,使用externals配置後,依舊能夠在代碼中經過CMD、AMD或者window/global全局的方式訪問。
npm install copy-webpack-plugin --save-dev //靜態資源輸出,將src目錄下的assets文件夾複製到dist目錄下 new copyWebpackPlugin([{ from: path.resolve(__dirname, "../src/assets"), to: './assets', ignore: ['.*'] }]),
npm install html-webpack-plugin --save-dev //修改webpack.base.conf.js代碼 // 獲取html-webpack-plugin參數的方法 var getHtmlConfig = function (name, chunks) { return { template: `./src/pages/${name}/index.html`, filename: `${name}.html`, // favicon: './favicon.ico', // title: title, inject: true, hash: true, //開啓hash ?[hash] chunks: chunks,//頁面要引入的包 minify: process.env.NODE_ENV === "development" ? false : { removeComments: true, //移除HTML中的註釋 collapseWhitespace: true, //摺疊空白區域 也就是壓縮代碼 removeAttributeQuotes: true, //去除屬性引用 }, }; }; //配置頁面 const htmlArray = [{ _html: 'index', title: '首頁', chunks: ['vendor', 'index']//頁面用到的vendor模塊 }, { _html: 'login', title: '登陸', chunks: ['login'] }, ]; //自動生成html模板 htmlArray.forEach((element) => { module.exports.plugins.push(new htmlWebpackPlugin(getHtmlConfig(element._html, element.chunks))); })
npm install webpack-bundle-analyzer --save-dev //修改 webpack.prod.conf.js代碼 new BundleAnalyzerPlugin() //npm run build 後會打開一個頁面
經過這個頁面能夠看到哪些頁面是由哪些模塊組成的,經過這個可視化頁面能夠更加方便去定位哪一個包臃腫了,而後去優化。webpack
Error: Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead
後來發現webpack4不支持extract-text-webpack-plugin 必須下載next版本安裝這個插件
npm install extract-text-webpack-plugin@next
https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/701css3