概念css
Webpack是一個模塊打包機,它能夠將咱們項目中的全部js、圖片、css等資源,根據其入口文件的依賴關係,打包成一個能被瀏覽器識別的js文件。可以幫助前端開發將打包的過程更智能化和自動化。html
WebPack和Grunt以及Gulp相比有什麼特性前端
Webpack和另外兩個並無太多的可比性,Gulp/Grunt是一種可以優化前端的開發流程的工具,而WebPack是一種模塊化的解決方案,不過Webpack的優勢使得Webpack在不少場景下能夠替代Gulp/Grunt類的工具。node
開始使用webpack
安裝webpack,目前webpack已更新到4.x版本,且大力度宣傳的是 cli 方式啓動,更推崇的是讓開發者使用高度封裝的 cli。基於此,咱們應該安裝webpack^4.1.一、webpack-cli^2.0.10
(想要執行webpack的命令必須有這個包)、webpack-dev-server^3.1.0。
ios
webpack的modees6
webpack4 的mode
給出了兩種配置:development
和production
。生產模式下,啓用了 代碼壓縮、做用域提高(scope hoisting)、 tree-shaking,使代碼最精簡;開發模式下,相較於更小體積的代碼,提供的是打包速度上的優化。因此,咱們通常配置2個文件,webpack.dev.conf.js和webpack.prod.conf.js。修改package.json裏面的scripts:web
"scripts": { "dev": "webpack --mode development", "build": "webpack --mode production" }
按項目搭建訴求加入配置npm
通常訴求:json
1.轉換js,解決兼容性問題,用 babel 轉換 ES6 代碼,用 babel 轉換 ES6 代碼須要使用到babel-loader,咱們須要安裝一系列的依賴:
npm i babel-core babel-loader babel-preset-env --save-dev
而後在根目錄新建一個babel配置文件.babelrc
:
{ "presets": [ [ "@babel/preset-env", { "targets": { "browsers": [ "last 2 iOS major versions", "last 2 Android major versions" ], "ios":"8.2" }, "exclude":["es6.promise"], "useBuiltIns": "usage", "debug": true } ] ], "plugins": ["@babel/transform-runtime"] }
Babel默認只轉換新的JavaScript語法,而不轉換新的API。 例如,Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise 等全局對象,以及一些定義在全局對象上的方法(好比 Object.assign)都不會轉譯。 若是想使用這些新的對象和方法,則須要爲當前環境提供一個polyfill。
解決方案一:
引入babel-polyfill,它會」加載整個polyfill庫」,針對編譯的代碼中新的API進行處理,而且在代碼中插入一些幫助函數。
解決方案二:
babel-runtime
兩種方案區別:
babel-polyfill解決了Babel不轉換新API的問題,可是直接在代碼中插入幫助函數,會致使污染了全局環境,而且不一樣的代碼文件中包含重複的代碼,致使編譯後的代碼體積變大。babel-runtime配置了以後,打包時會「按需加載」,當用到某個polifill時再引入對應的墊子,這樣能夠減小體積。但在某些狀況下仍然不能被babel-runtime替代, 例如,代碼:[1, 2, 3].includes(3),Object.assign({}, {key: 'value'}),Array,Object以及其餘」實例」下es6的方法,babel-runtime是沒法支持的, 由於babel-runtime只支持到static的方法。
所以,babel-runtime適合在組件,類庫項目中使用,而babel-polyfill適合在業務項目中使用。
babel-runtime版本搭配注意:
//安裝babel-runtime和babel-plugin-transform-runtime,配置以下: { "plugins": ["transform-runtime"] } //高版本的babel,安裝@babel/plugin-transform-runtime、@babel/runtime { "plugins": ["@babel/transform-runtime"] }
2.轉換css
相關的loder:less-loader、postcss-loader、css-loader、style-loader等。利用mini-css-extract-plugin來打包到一個文件裏面。參考代碼:
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = (env, argv) => { const devMode = argv.mode !== 'production' return { module: { rules: [ { test: /\.css$/, use: [ devMode ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader' ] }, ] }, plugins: [ new MiniCssExtractPlugin({ filename: "[name].css", chunkFilename: "[id].css" }) ] } }
3.處理html文件,通常用html-webpack-plugin,參考代碼:
const HtmlWebPackPlugin = require("html-webpack-plugin"); module.exports = { module: { rules: [ { test: /\.html$/, use: [{ loader: "html-loader", options: { minimize: true } }] } ] }, plugins: [ new HtmlWebPackPlugin({ template: "./src/index.html", filename: "./index.html" }) ] };
更多配置解釋,參考https://segmentfault.com/a/1190000007294861
4.清理
每次打包,都會生成項目的靜態資源,隨着某些文件的增刪,咱們的 dist 目錄下可能產生一些再也不使用的靜態資源,webpack並不會自動判斷哪些是須要的資源,爲了避免讓這些舊文件也部署到生產環境上佔用空間,因此在 webpack 打包前最好能清理 dist 目錄。
const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { plugins: [ new CleanWebpackPlugin(['dist']), ] };
5.資源處理
{ test: /\.html$/, loader: 'art-template-loader', }, { test: /\.jpg$/, loader: 'url-loader?mimetype=image/jpg' }, { test: /\.png$/, loader: 'url-loader?mimetype=image/png' }, { test: /\.svg/, loader: 'url-loader?mimetype=image/svg+xml' }
6.server的啓用
"scripts": { "start": "webpack-dev-server --mode development --open", "build": "webpack --mode production" }
7.開啓source-map
devtool: "inline-source-map" //詳細到打包前的每一個沒被壓縮的文件 or devtool: "source-map" //打包後的未壓縮文件
8.配置eslint
8.1要使webpack支持eslint,就要要安裝eslint-loader。
{ test: /\.js$/, loader: 'eslint-loader', enforce: "pre", include: [path.resolve(__dirname, 'src')], // 指定檢查的目錄 options: { // 這裏的配置項參數將會被傳遞到 eslint 的 CLIEngine formatter: require('eslint-friendly-formatter') // 指定錯誤報告的格式規範,formatter默認是stylish,若是想用第三方的要另外安裝 } }
8.2安裝eslint,建立配置文件 '.eslintrc.js'
module.exports = { 'root': true, 'plugins': [ 'html' ], 'settings': { 'html/html-extensions': ['.wxml'] }, 'rules': { 'newline-per-chained-call': 'off', 'eqeqeq': 'off', 'indent': ['error', 4, { SwitchCase: 1 }], 'prefer-rest-params': 'off', 'prefer-template': 'off', 'array-callback-return': 'off', // 暫時關閉 'prefer-const': 'warn', 'no-restricted-properties': [2, { 'object': 'wx', 'property': 'navigateTo', 'message': 'Please use this.$goto!!!' }] } }
更多詳細細節看文檔:http://eslint.cn/docs/user-guide
一、代碼壓縮,uglifyjs-webpack-plugin
new UglifyJsPlugin({ test: /.js$|.jsx$/i, uglifyOptions: { compress: { pure_funcs: ['console.log', 'alert'] }, }, })
2.提取公共模塊
output: { ... chunkFilename: '[name].[chunkhash:8].js' }, ... optimization: { splitChunks: { cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'common', chunks: 'all' } } } }
詳細參考:https://www.cnblogs.com/ufex/p/8758792.html
原文出處:https://www.cnblogs.com/LuckyWinty/p/10116497.html