webpack5公共資源路徑配置,環境變數,js壓縮
阿新 • • 發佈:2022-06-05
-
在未配置publicPath之前,index.html入口檔案中引入資源都是用相對路徑的
配置publicPath就可以指定公共資源路徑,這在部署釋出時很有用
module.exports = { entry: { // 多入口配置 index: './src/index.js', another: './src/another_module.js', }, output: { // filename: 'bundle.js', // 單入口 filename: 'scripts/[name].[contenthash].js', // 多入口 name就是entry配置的入口名(index、another)path: path.resolve(__dirname, './dist'), clean: true, // 每次打包清理dist目錄 assetModuleFilename: 'images/[contenthash][ext]', // contenthash:當前雜湊值 ext:源拓展名 publicPath: 'http://localhost:8080/' }, }
所有資源路徑前加上了publicPath
變成了絕對路徑
環境變數配置:
環境變數可以讓我們在開發環境和生產環境做出不同的webpack配置
可以在執行打包命令時加上環境變數引數 --env producttion
npx webpack --env production
然後把webpack.config.js中的module.exports改造成一個函式,這個函式有個引數,可以拿到環境變數
改造:
module.exports = (env) => { console.log(env); // { WEBPACK_BUNDLE: true, WEBPACK_BUILD: true, production: true } return { entry: { // 多入口配置 index: './src/index.js', another: './src/another_module.js', }, output: {// filename: 'bundle.js', // 單入口 filename: 'scripts/[name].[contenthash].js', // 多入口 name就是entry配置的入口名(index、another) path: path.resolve(__dirname, './dist'), clean: true, // 每次打包清理dist目錄 assetModuleFilename: 'images/[contenthash][ext]', // contenthash:當前雜湊值 ext:源拓展名 publicPath: 'http://localhost:8080/' },
} }
也可以加自定義引數
npx webpack --env production --env goal=local
列印如下:
{ WEBPACK_BUNDLE: true, WEBPACK_BUILD: true, production: true, goal: 'local' }
目前返現打包後的js沒有壓縮,webpack壓縮js不是開箱即用嗎?怎麼會沒壓縮呢?原因是我們之前配置了css壓縮,如果沒配置js壓縮,js就不會被壓縮,下面來配置下js壓縮。
js壓縮需要一個外掛
npm install terser-webpack-plugin -D
const path = require('path') const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin'); // 壓縮css,減小體積提升載入效率 const TerserPlugin = require('terser-webpack-plugin'); // js壓縮 module.exports = (env) => { console.log(env); return { entry: { // 多入口配置 index: './src/index.js', another: './src/another_module.js', }, output: { // filename: 'bundle.js', // 單入口 filename: 'scripts/[name].[contenthash].js', // 多入口 name就是entry配置的入口名(index、another) path: path.resolve(__dirname, './dist'), clean: true, // 每次打包清理dist目錄 assetModuleFilename: 'images/[contenthash][ext]', // contenthash:當前雜湊值 ext:源拓展名 publicPath: 'http://localhost:8080/' }, mode: env.production ? 'production' : 'development', devtool: 'inline-source-map', // 精準定位程式碼行數 optimization: { // 優化配置 minimizer: [ new CssMinimizerWebpackPlugin(), // css壓縮 new TerserPlugin(), // js壓縮 ], } } }
如果把mode改成development,即使配置了壓縮,也不壓縮了,因為只會在生產環境壓縮
-