Webpack5入门到原理20:Vue 脚手架搭建

2024-01-21 13:44

本文主要是介绍Webpack5入门到原理20:Vue 脚手架搭建,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

开发模式配置

// webpack.dev.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
const CopyPlugin = require("copy-webpack-plugin");const getStyleLoaders = (preProcessor) => {return ["vue-style-loader","css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env", // 能解决大多数样式兼容性问题],},},},preProcessor,].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: undefined,filename: "static/js/[name].js",chunkFilename: "static/js/[name].chunk.js",assetModuleFilename: "static/js/[hash:10][ext][query]",},module: {rules: [{// 用来匹配 .css 结尾的文件test: /\.css$/,// use 数组里面 Loader 执行顺序是从右到左use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},{test: /\.(png|jpe?g|gif|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024, // 小于10kb的图片会被base64处理},},},{test: /\.(ttf|woff2?)$/,type: "asset/resource",},{test: /\.(jsx|js)$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true,cacheCompression: false,plugins: [// "@babel/plugin-transform-runtime" // presets中包含了],},},// vue-loader不支持oneOf{test: /\.vue$/,loader: "vue-loader", // 内部会给vue文件注入HMR功能代码options: {// 开启缓存cacheDirectory: path.resolve(__dirname,"node_modules/.cache/vue-loader"),},},],},plugins: [new ESLintWebpackPlugin({context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname,"../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),new CopyPlugin({patterns: [{from: path.resolve(__dirname, "../public"),to: path.resolve(__dirname, "../dist"),toType: "dir",noErrorOnMissing: true,globOptions: {ignore: ["**/index.html"],},info: {minimized: true,},},],}),new VueLoaderPlugin(),// 解决页面警告new DefinePlugin({__VUE_OPTIONS_API__: "true",__VUE_PROD_DEVTOOLS__: "false",}),],optimization: {splitChunks: {chunks: "all",},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}`,},},resolve: {extensions: [".vue", ".js", ".json"], // 自动补全文件扩展名,让vue可以使用},devServer: {open: true,host: "localhost",port: 3000,hot: true,compress: true,historyApiFallback: true, // 解决vue-router刷新404问题},mode: "development",devtool: "cheap-module-source-map",
};

生产模式配置

// webpack.prod.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");const getStyleLoaders = (preProcessor) => {return [MiniCssExtractPlugin.loader,"css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env", // 能解决大多数样式兼容性问题],},},},preProcessor,].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: undefined,filename: "static/js/[name].[contenthash:10].js",chunkFilename: "static/js/[name].[contenthash:10].chunk.js",assetModuleFilename: "static/js/[hash:10][ext][query]",clean: true,},module: {rules: [{// 用来匹配 .css 结尾的文件test: /\.css$/,// use 数组里面 Loader 执行顺序是从右到左use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},{test: /\.(png|jpe?g|gif|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024, // 小于10kb的图片会被base64处理},},},{test: /\.(ttf|woff2?)$/,type: "asset/resource",},{test: /\.(jsx|js)$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true,cacheCompression: false,plugins: [// "@babel/plugin-transform-runtime" // presets中包含了],},},// vue-loader不支持oneOf{test: /\.vue$/,loader: "vue-loader", // 内部会给vue文件注入HMR功能代码options: {// 开启缓存cacheDirectory: path.resolve(__dirname,"node_modules/.cache/vue-loader"),},},],},plugins: [new ESLintWebpackPlugin({context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname,"../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),new CopyPlugin({patterns: [{from: path.resolve(__dirname, "../public"),to: path.resolve(__dirname, "../dist"),toType: "dir",noErrorOnMissing: true,globOptions: {ignore: ["**/index.html"],},info: {minimized: true,},},],}),new MiniCssExtractPlugin({filename: "static/css/[name].[contenthash:10].css",chunkFilename: "static/css/[name].[contenthash:10].chunk.css",}),new VueLoaderPlugin(),new DefinePlugin({__VUE_OPTIONS_API__: "true",__VUE_PROD_DEVTOOLS__: "false",}),],optimization: {// 压缩的操作minimizer: [new CssMinimizerPlugin(),new TerserWebpackPlugin(),new ImageMinimizerPlugin({minimizer: {implementation: ImageMinimizerPlugin.imageminGenerate,options: {plugins: [["gifsicle", { interlaced: true }],["jpegtran", { progressive: true }],["optipng", { optimizationLevel: 5 }],["svgo",{plugins: ["preset-default","prefixIds",{name: "sortAttrs",params: {xmlnsOrder: "alphabetical",},},],},],],},},}),],splitChunks: {chunks: "all",},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}`,},},resolve: {extensions: [".vue", ".js", ".json"],},mode: "production",devtool: "source-map",
};

其他配置

  • package.json
{"name": "vue-cli","version": "1.0.0","description": "","main": "main.js","scripts": {"start": "npm run dev","dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.dev.js","build": "cross-env NODE_ENV=production webpack --config ./config/webpack.prod.js"},"keywords": [],"author": "","license": "ISC","devDependencies": {"@babel/core": "^7.17.10","@babel/eslint-parser": "^7.17.0","@vue/cli-plugin-babel": "^5.0.4","babel-loader": "^8.2.5","copy-webpack-plugin": "^10.2.4","cross-env": "^7.0.3","css-loader": "^6.7.1","css-minimizer-webpack-plugin": "^3.4.1","eslint-plugin-vue": "^8.7.1","eslint-webpack-plugin": "^3.1.1","html-webpack-plugin": "^5.5.0","image-minimizer-webpack-plugin": "^3.2.3","imagemin": "^8.0.1","imagemin-gifsicle": "^7.0.0","imagemin-jpegtran": "^7.0.0","imagemin-optipng": "^8.0.0","imagemin-svgo": "^10.0.1","less-loader": "^10.2.0","mini-css-extract-plugin": "^2.6.0","postcss-preset-env": "^7.5.0","sass-loader": "^12.6.0","stylus-loader": "^6.2.0","vue-loader": "^17.0.0","vue-style-loader": "^4.1.3","vue-template-compiler": "^2.6.14","webpack": "^5.72.0","webpack-cli": "^4.9.2","webpack-dev-server": "^4.9.0"},"dependencies": {"vue": "^3.2.33","vue-router": "^4.0.15"},"browserslist": ["last 2 version", "> 1%", "not dead"]
}
  • .eslintrc.js
module.exports = {root: true,env: {node: true,},extends: ["plugin:vue/vue3-essential", "eslint:recommended"],parserOptions: {parser: "@babel/eslint-parser",},
};
  • babel.config.js
module.exports = {presets: ["@vue/cli-plugin-babel/preset"],
};

合并开发和生产配置

// webpack.config.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
const CopyPlugin = require("copy-webpack-plugin");// 需要通过 cross-env 定义环境变量
const isProduction = process.env.NODE_ENV === "production";const getStyleLoaders = (preProcessor) => {return [isProduction ? MiniCssExtractPlugin.loader : "vue-style-loader","css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env"],},},},preProcessor,].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: isProduction ? path.resolve(__dirname, "../dist") : undefined,filename: isProduction? "static/js/[name].[contenthash:10].js": "static/js/[name].js",chunkFilename: isProduction? "static/js/[name].[contenthash:10].chunk.js": "static/js/[name].chunk.js",assetModuleFilename: "static/js/[hash:10][ext][query]",clean: true,},module: {rules: [{// 用来匹配 .css 结尾的文件test: /\.css$/,// use 数组里面 Loader 执行顺序是从右到左use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},{test: /\.(png|jpe?g|gif|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024, // 小于10kb的图片会被base64处理},},},{test: /\.(ttf|woff2?)$/,type: "asset/resource",},{test: /\.(jsx|js)$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true,cacheCompression: false,plugins: [// "@babel/plugin-transform-runtime" // presets中包含了],},},// vue-loader不支持oneOf{test: /\.vue$/,loader: "vue-loader", // 内部会给vue文件注入HMR功能代码options: {// 开启缓存cacheDirectory: path.resolve(__dirname,"node_modules/.cache/vue-loader"),},},],},plugins: [new ESLintWebpackPlugin({context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname,"../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),new CopyPlugin({patterns: [{from: path.resolve(__dirname, "../public"),to: path.resolve(__dirname, "../dist"),toType: "dir",noErrorOnMissing: true,globOptions: {ignore: ["**/index.html"],},info: {minimized: true,},},],}),isProduction &&new MiniCssExtractPlugin({filename: "static/css/[name].[contenthash:10].css",chunkFilename: "static/css/[name].[contenthash:10].chunk.css",}),new VueLoaderPlugin(),new DefinePlugin({__VUE_OPTIONS_API__: "true",__VUE_PROD_DEVTOOLS__: "false",}),].filter(Boolean),optimization: {minimize: isProduction,// 压缩的操作minimizer: [new CssMinimizerPlugin(),new TerserWebpackPlugin(),new ImageMinimizerPlugin({minimizer: {implementation: ImageMinimizerPlugin.imageminGenerate,options: {plugins: [["gifsicle", { interlaced: true }],["jpegtran", { progressive: true }],["optipng", { optimizationLevel: 5 }],["svgo",{plugins: ["preset-default","prefixIds",{name: "sortAttrs",params: {xmlnsOrder: "alphabetical",},},],},],],},},}),],splitChunks: {chunks: "all",},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}`,},},resolve: {extensions: [".vue", ".js", ".json"],},devServer: {open: true,host: "localhost",port: 3000,hot: true,compress: true,historyApiFallback: true, // 解决vue-router刷新404问题},mode: isProduction ? "production" : "development",devtool: isProduction ? "source-map" : "cheap-module-source-map",
};

优化配置

const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");
// 需要通过 cross-env 定义环境变量
const isProduction = process.env.NODE_ENV === "production";const getStyleLoaders = (preProcessor) => {return [isProduction ? MiniCssExtractPlugin.loader : "vue-style-loader","css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env"],},},},preProcessor && {loader: preProcessor,options:preProcessor === "sass-loader"? {// 自定义主题:自动引入我们定义的scss文件additionalData: `@use "@/styles/element/index.scss" as *;`,}: {},},].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: isProduction ? path.resolve(__dirname, "../dist") : undefined,filename: isProduction? "static/js/[name].[contenthash:10].js": "static/js/[name].js",chunkFilename: isProduction? "static/js/[name].[contenthash:10].chunk.js": "static/js/[name].chunk.js",assetModuleFilename: "static/js/[hash:10][ext][query]",clean: true,},module: {rules: [{test: /\.css$/,use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},{test: /\.(png|jpe?g|gif|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024,},},},{test: /\.(ttf|woff2?)$/,type: "asset/resource",},{test: /\.(jsx|js)$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true,cacheCompression: false,plugins: [// "@babel/plugin-transform-runtime" // presets中包含了],},},// vue-loader不支持oneOf{test: /\.vue$/,loader: "vue-loader", // 内部会给vue文件注入HMR功能代码options: {// 开启缓存cacheDirectory: path.resolve(__dirname,"node_modules/.cache/vue-loader"),},},],},plugins: [new ESLintWebpackPlugin({context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname,"../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),new CopyPlugin({patterns: [{from: path.resolve(__dirname, "../public"),to: path.resolve(__dirname, "../dist"),toType: "dir",noErrorOnMissing: true,globOptions: {ignore: ["**/index.html"],},info: {minimized: true,},},],}),isProduction &&new MiniCssExtractPlugin({filename: "static/css/[name].[contenthash:10].css",chunkFilename: "static/css/[name].[contenthash:10].chunk.css",}),new VueLoaderPlugin(),new DefinePlugin({__VUE_OPTIONS_API__: "true",__VUE_PROD_DEVTOOLS__: "false",}),// 按需加载element-plus组件样式AutoImport({resolvers: [ElementPlusResolver()],}),Components({resolvers: [ElementPlusResolver({importStyle: "sass", // 自定义主题}),],}),].filter(Boolean),optimization: {minimize: isProduction,// 压缩的操作minimizer: [new CssMinimizerPlugin(),new TerserWebpackPlugin(),new ImageMinimizerPlugin({minimizer: {implementation: ImageMinimizerPlugin.imageminGenerate,options: {plugins: [["gifsicle", { interlaced: true }],["jpegtran", { progressive: true }],["optipng", { optimizationLevel: 5 }],["svgo",{plugins: ["preset-default","prefixIds",{name: "sortAttrs",params: {xmlnsOrder: "alphabetical",},},],},],],},},}),],splitChunks: {chunks: "all",cacheGroups: {// layouts通常是admin项目的主体布局组件,所有路由组件都要使用的// 可以单独打包,从而复用// 如果项目中没有,请删除layouts: {name: "layouts",test: path.resolve(__dirname, "../src/layouts"),priority: 40,},// 如果项目中使用element-plus,此时将所有node_modules打包在一起,那么打包输出文件会比较大。// 所以我们将node_modules中比较大的模块单独打包,从而并行加载速度更好// 如果项目中没有,请删除elementUI: {name: "chunk-elementPlus",test: /[\\/]node_modules[\\/]_?element-plus(.*)/,priority: 30,},// 将vue相关的库单独打包,减少node_modules的chunk体积。vue: {name: "vue",test: /[\\/]node_modules[\\/]vue(.*)[\\/]/,chunks: "initial",priority: 20,},libs: {name: "chunk-libs",test: /[\\/]node_modules[\\/]/,priority: 10, // 权重最低,优先考虑前面内容chunks: "initial",},},},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}`,},},resolve: {extensions: [".vue", ".js", ".json"],alias: {// 路径别名"@": path.resolve(__dirname, "../src"),},},devServer: {open: true,host: "localhost",port: 3000,hot: true,compress: true,historyApiFallback: true, // 解决vue-router刷新404问题},mode: isProduction ? "production" : "development",devtool: isProduction ? "source-map" : "cheap-module-source-map",performance: false,
};

这篇关于Webpack5入门到原理20:Vue 脚手架搭建的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/629731

相关文章

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

【 html+css 绚丽Loading 】000046 三才归元阵

前言:哈喽,大家好,今天给大家分享html+css 绚丽Loading!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 📚一、效果📚二、信息💡1.简介:💡2.外观描述:💡3.使用方式:💡4.战斗方式:💡5.提升:💡6.传说: 📚三、源代码,上代码,可以直接复制使用🎥效果🗂️目录✍️

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

hdu4407(容斥原理)

题意:给一串数字1,2,......n,两个操作:1、修改第k个数字,2、查询区间[l,r]中与n互质的数之和。 解题思路:咱一看,像线段树,但是如果用线段树做,那么每个区间一定要记录所有的素因子,这样会超内存。然后我就做不来了。后来看了题解,原来是用容斥原理来做的。还记得这道题目吗?求区间[1,r]中与p互质的数的个数,如果不会的话就先去做那题吧。现在这题是求区间[l,r]中与n互质的数的和

搭建Kafka+zookeeper集群调度

前言 硬件环境 172.18.0.5        kafkazk1        Kafka+zookeeper                Kafka Broker集群 172.18.0.6        kafkazk2        Kafka+zookeeper                Kafka Broker集群 172.18.0.7        kafkazk3

数论入门整理(updating)

一、gcd lcm 基础中的基础,一般用来处理计算第一步什么的,分数化简之类。 LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } <pre name="code" class="cpp">LL lcm(LL a, LL b){LL c = gcd(a, b);return a / c * b;} 例题:

Java 创建图形用户界面(GUI)入门指南(Swing库 JFrame 类)概述

概述 基本概念 Java Swing 的架构 Java Swing 是一个为 Java 设计的 GUI 工具包,是 JAVA 基础类的一部分,基于 Java AWT 构建,提供了一系列轻量级、可定制的图形用户界面(GUI)组件。 与 AWT 相比,Swing 提供了许多比 AWT 更好的屏幕显示元素,更加灵活和可定制,具有更好的跨平台性能。 组件和容器 Java Swing 提供了许多