webpack4-1.常见配置

参看:文档地址

视频地址:https://www.bilibili.com/video/av51693431

webpack的作用:代码转换、文件优化、代码分割、模块管理、自动刷新、代码检验、自动发布

2 webpack 常见配置

2.1 安装

npm init -ycnpm i webpack webpack-cli -D# 版本# "webpack": "^4.41.4"# "webpack-cli": "^3.3.10"# webpack 打包命令npx webpack

2.2 配置

// webpack.config.jsconst path = require(‘path‘)module.exports = { mode: ‘development‘, // development production(该模式下回自动压缩代码) entry: path.join(__dirname, ‘./src/index.js‘), output: { filename: ‘bundle.[hash:8].js‘, path: path.join(__dirname, ‘./build‘), }}

2.2.1 自定义打包配置文件

// webpack.config.xxx.jsmodule.exports = { // ...}// 执行命令// npx webpack --config webpack.config.xxx.js

2.2.2 配置脚本

{
"scripts": { "dev": "webpack-dev-server --config webpack.config.js --colors", "build": "webpack --config webpack.config.js --colors" }}

2.3 常用插件

webpack-dev-server

cnpm i webpack-dev-server -D

devServer: { port: 8081, progress: true, // 进度条 contentBase: ‘./build‘, // 指定 build 文件夹作为静态服务 compress: true // 压缩文件}

html-webpack-plugin - 打包 html 页面:

cnpm i html-webpack-plugin -D

const HtmlWebpackPlugin = require(‘html-webpack-plugin‘)module.exports = { // ... plugins: [ new HtmlWebpackPlugin({ template: ‘./src/index.html‘, filename: ‘index.html‘, minify: { removeAttributeQuotes: true, // 删除双引号 collapseWhitespace: true // 折叠空行 }, hash: true // 添加 hash 戳 }) ] // ...}

css less loader 配置

cnpm i css-loader less less-loader mini-css-extract-plugin postcss-loader style-loader url-loader -D

const MiniCssExtractPlugin = require("mini-css-extract-plugin")module.exports = { // ... plugins: [ new MiniCssExtractPlugin({ filename: path.posix.join(‘static‘, ‘css/[name].[contenthash].css‘), // disable: false, //是否禁用此插件 // allChunks: true, // publicPath: ‘‘, options: { insert: ‘head‘ } }) ], module: { rules: [ { // css test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { // localIdentName:‘[name]-[local]-[hash:base64:6]‘, publicPath: ‘../../‘ } }, { loader: ‘css-loader‘, options: { url: true, modules: {} } }, ‘postcss-loader‘ ] }, { // less test: /\.less$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { publicPath: ‘../../‘ } }, { loader: ‘css-loader‘, options: {} }, ‘less-loader‘, ‘postcss-loader‘ ] }, ] } // ...}

postcss.config.js

module.exports = { plugins: { ‘autoprefixer‘: { overrideBrowserslist: ‘last 5 version‘ } }}

postcss-loader 配合autoprefixer给样式加前缀。

打包 JS CSS 压缩优化:

const OptimizeCSSAssetsPlugin = require(‘optimize-css-assets-webpack-plugin‘) // 用于优化\最小化CSSconst TerserJSPlugin = require(‘terser-webpack-plugin‘) // js 压缩module.exports = { // ... optimization: { minimize: true, minimizer: [ new TerserJSPlugin({ cache: true, // 是否缓存 parallel: true, // 并发打包 sourceMap: true, }), new OptimizeCSSAssetsPlugin({ cssProcessorPluginOptions: { preset: [‘default‘, { discardComments: { removeAll: true } }], }, cssProcessorOptions: { safe: true } }) ] }, // ...}

2.4 ES6 语法转换

cnpm i @babel/preset-env @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties @babel/plugin-transform-runtime -D

cnpm i @babel/runtime -S

@babel/polyfill 已弃用,参看:core-js@3带来的惊喜corejs

require("core-js-pure/stable")require("regenerator-runtime/runtime")module.exports = { // ... module: { rules: [ { test: /\.js$/, use: { loader: ‘babel-loader‘, options: { presets: [ // 预设 ["@babel/preset-env", { "useBuiltIns": "usage", "targets": { "chrome": "58", "ie": "11" } }] ], plugins: [ [‘@babel/plugin-proposal-decorators‘, {‘legacy‘: true}], // 装饰器 [‘@babel/plugin-proposal-class-properties‘, {‘loose‘: true}], // Class "@babel/plugin-transform-runtime" ] } }, include: path.resolve(__dirname, ‘src‘), exclude: /node_modules/ }, ] } // ...}

 

2.5 代码规范

cnpm i eslint eslint-loader -D

// webpack.config.jsmodule.exports = { // ... module: { rules: [ { test: /\.js$/, enforce: ‘pre‘, // previous post,在mormal loader 前置执行 use: { loader: ‘eslint-loader‘, options: { cache: true, fix: true // ESLint自动修复功能 } }, enforce: ‘pre‘, // previous post exclude: /node_modules/ } ] } // ...}

官方配置地址 => Rules Configuration

// .eslintrc.json{ "parserOptions": { "ecmaVersion": 11, "sourceType": "module", "ecmaFeatures": { "globalReturn": true } }, "rules": { }, "env": { "node": true, "commonjs": true, "es6": true }}

2.6 第三方模块使用

以依赖于 jquery 为类,将module中的模块挂载到window上。

cnpm i jquery -S

  • 方法一
// expose-loader 暴露全局的loader/内联的loader 到 window上import $ from ‘expose-loader?$!jquery‘// pre 前面执行的loader normal--普通loader/内联loader/后置post-loaderconsole.log(‘window.$‘,window.$) // 类似于 CDN 引入文件
  • 方法二
import $ from ‘jquery‘console.log(‘window.$‘,window.$)

配置:

// webpack.config.jsmodule.exports = { // ... module: { rules: [ { // 将 jquery 暴露给 window test: require.resolve(‘jquery‘), use: ‘expose-loader?$‘ } ] } // ...}
  • 方法三:在每个模块中注入$ 对象,不打包jquery
console.log(‘$‘, $) // 在模块中使用,但是 $ 不存在window中
// webpack.config.jsmodule.exports = { // ... plugins: [ new Webpack.ProvidePlugin({ // 在每个模块注入 $ 对象 "$": "jquery" }) ] // ...}
  • 方法四:CDN 引入:
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>

防止在模块中多次import jquery,导致打包体积变大:

// webpack.config.jsmodule.exports = { // ... externals: { // 不打包 jquery jquery: ‘jquery‘ } // ...}

2.4 webpack打包图片

js中生成图片、在css插入图片、在html中插入图片

// webpack.config.jsmodule.exports = { // ... module: { rules: [ { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, use: { loader: ‘url-loader‘, options: { name: path.posix.join(‘static‘, ‘img/[name].[hash:7].[ext]‘), esModule: false, limit: 5 * 1024, // outputPath: ‘img/‘, // name: ‘[name].[hash:7].[ext]‘, // publicPath:‘img/‘ // publicPath: ‘http://www.houfee.top/‘ // 只为打包的图片添加 地址路径 } } }, ] } // ...}

相关文章