上一章我们了解过了webpack5的基本配置,下面我们用webpack5进一步配置一个vue项目
git地址:vue-template
技术栈: Vue2.x+webapck5+Eslint+Jest + prettier + yarn +vscode
包含的功能:
-
env 文件夹内 配置不同环境的全局变量
-
config 配置不同的环境的构建
-
jsconfig.json 可以解决 resolve中别名路径问题
-
eslint 代码风格统一
-
jest 单元测试
-
crypto-js 引入问题
-
加入缓存
-
使用css module
-
热更新问题
这个是项目的目录
这个是packge.json文件
{
"name": "vue-template", "version": "1.0.0", "main": "index.js", "repository": "", "license": "MIT", "sideEffects": false, "scripts": { "start": "cross-env NODE_ENV=development webpack serve --config config/config.js", "build": "cross-env NODE_ENV=production webpack --config config/config.js", "lint": "eslint --ext .js,.vue src", "lint-fix": "eslint --fix --ext .js,.vue src", "test": "jest" }, "devDependencies": { "@babel/core": "^7.12.13", "@babel/plugin-transform-runtime": "^7.12.15", "@babel/preset-env": "^7.12.13", "@babel/runtime-corejs3": "^7.12.13", "@vue/test-utils": "^1.1.3", "autoprefixer": "6.x", "babel-core": "^6.26.3", "babel-eslint": "^10.1.0", "babel-jest": "^26.6.3", "babel-loader": "^8.2.2", "babel-plugin-component": "^1.1.1", "clean-webpack-plugin": "^3.0.0", "cross-env": "^7.0.3", "css-loader": "^5.0.1", "css-minimizer-webpack-plugin": "^1.2.0", "eslint": "^7.19.0", "eslint-config-prettier": "^7.2.0", "eslint-loader": "^4.0.2", "eslint-plugin-prettier": "^3.3.1", "eslint-plugin-vue": "^7.5.0", "file-loader": "^6.2.0", "friendly-errors-webpack-plugin": "^1.7.0", "html-webpack-plugin": "^5.0.0", "husky": "^4.3.8", "jest": "^26.6.3", "jest-serializer-vue": "^2.0.2", "jest-transform-stub": "^2.0.0", "lint-staged": "^10.5.4", "mini-css-extract-plugin": "^1.3.5", "node-sass": "^5.0.0", "postcss-loader": "4.1.0", "prettier": "^2.2.1", "sass": "^1.32.6", "sass-loader": "^11.0.0", "sass-resources-loader": "^2.1.1", "style-loader": "^2.0.0", "thread-loader": "^3.0.1", "url-loader": "^4.1.1", "vue-eslint-parser": "^7.4.1", "vue-jest": "^3.0.7", "vue-loader": "^15.9.6", "vue-template-compiler": "^2.6.12", "webpack": "^5.21.1", "webpack-bundle-analyzer": "^4.4.0", "webpack-cli": "^4.5.0", "webpack-dev-server": "^3.11.2", "webpack-merge": "^5.7.3" }, "dependencies": {
"crypto-js": "^4.0.0", "vue": "^2.6.12", "vue-router": "^3.5.1" }
}
如上安装使用 yarn install
安装成功后直接运行 yarn run start
1.公用配置
config/bash.js
const path = require('path');const webpack = require('webpack');const HtmlWebpackPlugin = require('html-webpack-plugin');const VueLoaderPlugin = require('vue-loader/lib/plugin');const MiniCssExtractPlugin = require('mini-css-extract-plugin');const { CleanWebpackPlugin } = require('clean-webpack-plugin');module.exports = { entry: { main: './src/index.js' }, output: { filename: 'js/[name].min.js', chunkFilename: 'js/chunk/[name].js', publicPath: '/', path: path.resolve(__dirname, '..', 'dist') }, module: { rules: [
{ test: /\.(js|vue)$/, loader: 'eslint-loader', exclude: /node_modules/, enforce: 'pre' }, { // 添加解析 .vue文件loader test: /\.vue$/, loader: 'vue-loader', include: [path.resolve(__dirname, '../src')], options: assetsRequire }, { test: /\.js(\?.*)?$/, exclude: (file) => /node_modules/.test(file) && !/\.vue\.js/.test(file), use: { loader: 'babel-loader' } }, { test: /\.css$/, include: [path.resolve(__dirname, '../src')], sideEffects: true, use:[process.env.NODE_ENV === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'] }, { test: /\.s[ac]ss$/i, include: [path.resolve(__dirname, '../src'), path.resolve(__dirname, '../node_modules/_element-ui')], sideEffects: true, use:[process.env.NODE_ENV === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader',''sass-loader'] }, { test: /\.(|woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: [ { loader: 'file-loader', options: { esModule: false, limit: 2048, name: 'assets/fonts/[name].[ext]', publicPath: '/' } } ] }, { test: /\.(png|jpg|gif|svg|ico)$/i, //正则表达式匹配图片规则 use: [ { loader: 'url-loader', options: { esModule: false, limit: 2048, name: 'assets/images/[name].[ext]', //images:图片打包的文件夹; publicPath: '/' } } ] } ] }, resolve: { extensions: ['.js', '.vue', '.scss', '.css'], alias: { '@': path.resolve(__dirname, '..', 'src/'), } }, plugins: [ new webpack.DefinePlugin({ // 定义环境和变量 'process.env': { } }), new MiniCssExtractPlugin({ filename: 'css/[name].[contenthash:8].css', chunkFilename: 'css/[name].[contenthash:8].css' }), new HtmlWebpackPlugin({ template: path.join(__dirname, '../public/index.html'), favicon: path.join(__dirname, '../public/favicon.ico'), //favicon路径 filename: 'index.html', chunks: ['main'], inject: true, minify: true, cache: false, hash: true //开启hash ?[hash] }), new VueLoaderPlugin() ]};
解析:其中大部分就不介绍了,eslint-loader这个配置是为了每次解析前判断代码是否符合eslint设置的规则,如果不符合则不往下进行
2.开发环境
config/dev.js的配置
const path = require('path');const webpack = require('webpack');module.exports = { mode: 'development', cache: { type: 'memory' }, target: 'web', devtool: 'eval-cheap-module-source-map', plugins: [ new webpack.HotModuleReplacementPlugin(), ], optimization: { usedExports: true }, devServer: { // 启动devServer,不会在本地生成文件,所有文件会编译在内存中(读取速度快) contentBase: path.join(__dirname, '../dist'), //静态文件根目录 overlay: true, // 错误信息直接显示在浏览器窗口中 port: 1111, stats: 'errors-only', publicPath: '/', inline: true, // 实时重载的脚本被插入到你的包(bundle)中,并且构建消息将会出现在浏览器控制台 hot: true, // 配合webpack.NamedModulesPlugin、webpack.HotModuleReplacementPlugin完成MHR host: '0.0.0.0', // 设置为0.0.0.0并配合useLocalIp可以局域网访问 useLocalIp: true, // 使用本机IP打开devServer,而不是localhost open: 'chrome', historyApiFallback: true //history 路由,hash不需要 }};
然后进行如上的配置,在本都开启一个服务,作为开发的配置的环境
3.生产环境
config/pro.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin');const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');const path = require('path');module.exports = { stats: 'none', mode: 'production', devtool: 'cheap-module-source-map', cache: { type: 'filesystem', cacheDirectory: path.resolve(__dirname, '../.temp_cache'), buildDependencies: { // 将你的配置添加依赖,更改配置时,使得缓存失效 config: [__filename] } }, plugins: [ new CleanWebpackPlugin({ cleanOnceBeforeBuildPatterns: [path.resolve(process.cwd(), 'build/'), path.resolve(process.cwd(), 'dist/')] }) ], optimization: { minimize: true, minimizer: [ new CssMinimizerPlugin({ cache: true }) ] }};
这个是生产环境的配置,进行缓存,可以提高二次打包的速度
4.配置eslint
我们需要安装eslint相关的npm包
yarn add babel-eslint eslint eslint-config-prettier eslint-loader prettier eslint-plugin-prettier eslint-plugin-vue vue-eslint-parser -D
安装完成后
.eslintrc.js
module.exports = { root: true, env: { browser: true, es2021: true }, extends: ['plugin:vue/essential', 'eslint:recommended', 'plugin:prettier/recommended'], parser: 'vue-eslint-parser', parserOptions: { parser: 'babel-eslint', ecmaVersion: 12, sourceType: 'module' }, plugins: ['vue'], rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'vue/html-indent': 'off', 'comma-dangle': ['error', 'never'], quotes: ['error', 'single'] }, globals: { process: true }};