• webpack搭建vue脚手架


    初始化项目

    npm init -y
    

    安装webpack相关

    npm i  webpack webpack-cli webpack-dev-server -D

    安装解析vue的插件

    npm i vue  vue-loader vue-template-compiler vue-style-loader -D
    

    根目录下创建webpack.config.js文件

    这里注意vue-loader不支持oneOf 不然会报错

    1. const path = require('path')
    2. // 引入vue-loader的内置插件
    3. const {VueLoaderPlugin} = require('vue-loader')
    4. module.exports = {
    5. // 配置入口文件
    6. entry:'./src/main.js',
    7. // 配置文件的出口
    8. output:{
    9. path:path.resolve(__dirnamem, 'dist'),
    10. filename:'main.js'
    11. },
    12. // 配置loader
    13. module:{
    14. rules:[
    15. {
    16. test:/\.vue$/i,
    17. use:['vue-loader']
    18. }
    19. ]
    20. },
    21. plugins:[
    22. new VueLoaderPlugin(),
    23. ]
    24. }

    创建html模板

    1. public/index.html
    2. <!DOCTYPE html>
    3. <html lang="en">
    4. <head>
    5. <meta charset="UTF-8">
    6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    8. <title>Document</title>
    9. </head>
    10. <body>
    11. <div id="app"></div>
    12. </body>
    13. </html>

    安装解析生产html插件

    npm i  html-webpack-plugin --save-dev
    

    配置

    1. // 引入 html-webpack-plugin
    2. const HtmlWebpackPlugin = require('html-webpack-plugin')
    3. new HtmlWebpackPlugin({
    4. template: path.resolve(__dirname, "../public/index.html"),
    5. }),

    解析样式

    npm i css-loader less-loader postcss-loader postcss-preset-env style-loader --save-dev
    
    1. {
    2. test:/\.vue$/i,
    3. loader: 'vue-loader'
    4. },
    5. {
    6. test:/\.css$/i,
    7. use:['stylel-loader', 'css-loader']
    8. },
    9. {
    10. test:/\.less$/i,
    11. use:['stylel-loader''css-loader', 'less-loader']
    12. },

    安装postcss-preset-env 能解决css大多数样式兼容性问题 需要和packjson.js中的browserslist指定兼容性配合使用

    1. packjson.js
    2. "browserslist": [
    3. "last 2 version",
    4. "> 1%",
    5. "not dead"
    6. ]

    封装样式loader

    1. const getStyleLoaders = (pre) => {
    2. return [
    3. "style-loader",
    4. "css-loader",
    5. {
    6. loader: "postcss-loader",
    7. options: {
    8. postcssOptions: {
    9. plugins: [
    10. "postcss-preset-env", // 需要安装postcss-preset-env 能解决css大多数样式兼容性问题 和packjson.js中的browserslist来指定兼容性
    11. ],
    12. },
    13. },
    14. },
    15. pre
    16. ].filter(Boolean);
    17. };
    1. {
    2. test:/\.vue$/i,
    3. loader: 'vue-loader'
    4. },
    5. {
    6. test:/\.css$/i,
    7. use: getStyleLoaders()
    8. },
    9. {
    10. test:/\.less$/i,
    11. use: getStyleLoaders("less-loader"),
    12. },

    处理图片

    1. npm i image-minimizer-webpack-plugin imagemin
    2. 无损压缩
    3. npm install imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo -D
    1. {
    2. test: /\.(png|jpe?g|gif|svg)$/,
    3. type: "asset",
    4. parser: {
    5. dataUrlCondition: {
    6. maxSize: 10 * 1024, // 小于10kb的图片会被转为base64处理
    7. },
    8. },
    9. },
    1. const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");//压缩图片
    2. optimization: {
    3. minimizer: [
    4. // 压缩图片
    5. new ImageMinimizerPlugin({
    6. minimizer: {
    7. implementation: ImageMinimizerPlugin.imageminGenerate,
    8. options: {
    9. plugins: [
    10. ["gifsicle", { interlaced: true }],
    11. ["jpegtran", { progressive: true }],
    12. ["optipng", { optimizationLevel: 5 }],
    13. [
    14. "svgo",
    15. {
    16. plugins: [
    17. "preset-default",
    18. "prefixIds",
    19. {
    20. name: "sortAttrs",
    21. params: {
    22. xmlnsOrder: "alphabetical",
    23. },
    24. },
    25. ],
    26. },
    27. ],
    28. ],
    29. },
    30. },
    31. }),
    32. ],
    33. },

    这里也可以不做图片的压缩配置,自己手动压缩图片

    压缩css并提取css成单独文件

    npm i css-minimizer-webpack-plugin mini-css-extract-plugin -D
    1. const MiniCssExtractPlugin = require("mini-css-extract-plugin");//将css代码单独打包
    2. const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");//css压缩
    3. //提取css成单独文件
    4. const getStyleLoaders = (pre) => {
    5. return [
    6. MiniCssExtractPlugin.loader,//修改
    7. "css-loader",
    8. {
    9. loader: "postcss-loader",
    10. options: {
    11. postcssOptions: {
    12. plugins: [
    13. "postcss-preset-env",
    14. ],
    15. },
    16. },
    17. },
    18. pre
    19. ].filter(Boolean);
    20. };
    21. 压缩css
    22. new MiniCssExtractPlugin({
    23. filename: 'static/css/[name].[contenthash:10].css',
    24. chunkFilename: 'static/css/[name].[contenthash:10].chunk.css'
    25. }),
    26. minimizer: [
    27. new CssMinimizerPlugin(),//css压缩
    28. new TerserWebpackPlugin(),//js压缩 因为css压缩了不压缩代码会有问题
    29. new ImageMinimizerPlugin({
    30. ...
    31. }),
    32. ]

    配置eslint 和babel处理js文件

    npm i babel-loader eslint-webpack-plugin  eslint eslint-webpack-plugin eslint-plugin-vue

    创建.eslintrc.js和babel.config.js

    eslintrc.js

    1. module.exports = {
    2. root: true,
    3. env: {
    4. node: true,
    5. },
    6. extends: ["plugin:vue/vue3-essential", "eslint:recommended"],
    7. parserOptions: {
    8. parser: "@babel/eslint-parser",
    9. },
    10. };

    babel.config.js

    1. module.exports = {
    2. presets: ["@vue/cli-plugin-babel/preset"],
    3. };
    1. {
    2. test: /\.(jsx|js)$/,
    3. include: path.resolve(__dirname, "../src"),
    4. loader: "babel-loader",
    5. options: {
    6. cacheDirectory: true,
    7. cacheCompression: false,
    8. },
    9. },
    const ESLintWebpackPlugin = require("eslint-webpack-plugin");
    1. new ESLintWebpackPlugin({
    2. context: path.resolve(__dirname, "../src"),处理src文件夹中的内容
    3. exclude: "node_modules",//不处理node_modules文件夹中的内容
    4. //开启缓存
    5. cache: true,
    6. cacheLocation: path.resolve(
    7. __dirname,
    8. "../node_modules/.cache/.eslintcache"//缓存文件路径
    9. ),
    10. }),

    环境变量处理

    npm i cross-env
    1. // 需要通过 cross-env 定义环境变量 获取环境变量
    2. const isProduction = process.env.NODE_ENV === "production";

    packjson.js

    1. "scripts": {
    2. "start": "npm run dev",
    3. //开发模式
    4. "dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.config.js",
    5. //生产模式
    6. "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.config.js"
    7. },

    webpack.config.js

    1. // 需要通过 cross-env 定义环境变量 获取环境变量
    2. const isProduction = process.env.NODE_ENV === "production";
    3. const { DefinePlugin } = require("webpack");
    4. //定义环境变量
    5. //cross-eny定义的环境变量给webpack打包工具使用
    6. //DefinePlugin 定义的环境变量才是给源代码使用的 从而解决vue3页面警告的问题
    7. new DefinePlugin({
    8. __VUE_OPTIONS_API__: true,
    9. __VUE_PROD_DEVTOOLS__: false
    10. }),

    处理图标

    在index中引入

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <link rel="short icon" href="favicon.ico">
    8. <title>reactcli</title>
    9. </head>
    10. <body>
    11. <div id="app"></div>
    12. </body>
    13. </html>

    这还不能实现效果,因为webpack只打包了src下的文件,index.html所处的public文件不会处理,

    单纯只是引入找不到public下的图标文件

    通过copyplugin处理

    1. const CopyPlugin = require("copy-webpack-plugin");//webpack没有处理public文件夹下文件 所有我们直接复制过去
    2. // 将public下面的资源复制到dist目录去(除了index.html)
    3. new CopyPlugin({
    4. patterns: [
    5. {
    6. from: path.resolve(__dirname, "../public"),
    7. to: path.resolve(__dirname, "../dist"),
    8. toType: "dir",
    9. noErrorOnMissing: true, // 不生成错误
    10. globOptions: {
    11. // 忽略文件
    12. ignore: ["**/index.html"],
    13. },
    14. info: {
    15. // 跳过terser压缩js
    16. minimized: true,
    17. },
    18. },
    19. ],
    20. }),
    21. ].filter(Boolean)

    根据环境变量配置开发模式和生产模式下配置

    1. // webpack.config.js
    2. const path = require("path");
    3. const ESLintWebpackPlugin = require("eslint-webpack-plugin");
    4. const HtmlWebpackPlugin = require("html-webpack-plugin");
    5. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    6. const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
    7. const TerserWebpackPlugin = require("terser-webpack-plugin");
    8. const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
    9. const { VueLoaderPlugin } = require("vue-loader");
    10. const { DefinePlugin } = require("webpack");
    11. const CopyPlugin = require("copy-webpack-plugin");
    12. // 需要通过 cross-env 定义环境变量
    13. const isProduction = process.env.NODE_ENV === "production";
    14. const getStyleLoaders = (preProcessor) => {
    15. return [
    16. isProduction ? MiniCssExtractPlugin.loader : "vue-style-loader",
    17. "css-loader",
    18. {
    19. loader: "postcss-loader",
    20. options: {
    21. postcssOptions: {
    22. plugins: ["postcss-preset-env"],
    23. },
    24. },
    25. },
    26. preProcessor,
    27. ].filter(Boolean);
    28. };
    29. module.exports = {
    30. entry: "./src/main.js",
    31. output: {
    32. path: isProduction ? path.resolve(__dirname, "../dist") : undefined,
    33. filename: isProduction
    34. ? "static/js/[name].[contenthash:10].js"
    35. : "static/js/[name].js",
    36. chunkFilename: isProduction
    37. ? "static/js/[name].[contenthash:10].chunk.js"
    38. : "static/js/[name].chunk.js",
    39. assetModuleFilename: "static/js/[hash:10][ext][query]",
    40. clean: true,
    41. },
    42. module: {
    43. rules: [
    44. {
    45. // 用来匹配 .css 结尾的文件
    46. test: /\.css$/,
    47. // use 数组里面 Loader 执行顺序是从右到左
    48. use: getStyleLoaders(),
    49. },
    50. {
    51. test: /\.less$/,
    52. use: getStyleLoaders("less-loader"),
    53. },
    54. {
    55. test: /\.s[ac]ss$/,
    56. use: getStyleLoaders("sass-loader"),
    57. },
    58. {
    59. test: /\.styl$/,
    60. use: getStyleLoaders("stylus-loader"),
    61. },
    62. {
    63. test: /\.(png|jpe?g|gif|svg)$/,
    64. type: "asset",
    65. parser: {
    66. dataUrlCondition: {
    67. maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
    68. },
    69. },
    70. },
    71. {
    72. test: /\.(ttf|woff2?)$/,
    73. type: "asset/resource",
    74. },
    75. {
    76. test: /\.(jsx|js)$/,
    77. include: path.resolve(__dirname, "../src"),
    78. loader: "babel-loader",
    79. options: {
    80. cacheDirectory: true,
    81. cacheCompression: false,
    82. plugins: [
    83. // "@babel/plugin-transform-runtime" // presets中包含了
    84. ],
    85. },
    86. },
    87. // vue-loader不支持oneOf
    88. {
    89. test: /\.vue$/,
    90. loader: "vue-loader", // 内部会给vue文件注入HMR功能代码
    91. options: {
    92. // 开启缓存
    93. cacheDirectory: path.resolve(
    94. __dirname,
    95. "node_modules/.cache/vue-loader"
    96. ),
    97. },
    98. },
    99. ],
    100. },
    101. plugins: [
    102. new ESLintWebpackPlugin({
    103. context: path.resolve(__dirname, "../src"),
    104. exclude: "node_modules",
    105. cache: true,
    106. cacheLocation: path.resolve(
    107. __dirname,
    108. "../node_modules/.cache/.eslintcache"
    109. ),
    110. }),
    111. new HtmlWebpackPlugin({
    112. template: path.resolve(__dirname, "../public/index.html"),
    113. }),
    114. new CopyPlugin({
    115. patterns: [
    116. {
    117. from: path.resolve(__dirname, "../public"),
    118. to: path.resolve(__dirname, "../dist"),
    119. toType: "dir",
    120. noErrorOnMissing: true,
    121. globOptions: {
    122. ignore: ["**/index.html"],
    123. },
    124. info: {
    125. minimized: true,
    126. },
    127. },
    128. ],
    129. }),
    130. isProduction &&
    131. new MiniCssExtractPlugin({
    132. filename: "static/css/[name].[contenthash:10].css",
    133. chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
    134. }),
    135. new VueLoaderPlugin(),
    136. new DefinePlugin({
    137. __VUE_OPTIONS_API__: "true",
    138. __VUE_PROD_DEVTOOLS__: "false",
    139. }),
    140. ].filter(Boolean),
    141. optimization: {
    142. minimize: isProduction,
    143. // 压缩的操作
    144. minimizer: [
    145. new CssMinimizerPlugin(),
    146. new TerserWebpackPlugin(),
    147. new ImageMinimizerPlugin({
    148. minimizer: {
    149. implementation: ImageMinimizerPlugin.imageminGenerate,
    150. options: {
    151. plugins: [
    152. ["gifsicle", { interlaced: true }],
    153. ["jpegtran", { progressive: true }],
    154. ["optipng", { optimizationLevel: 5 }],
    155. [
    156. "svgo",
    157. {
    158. plugins: [
    159. "preset-default",
    160. "prefixIds",
    161. {
    162. name: "sortAttrs",
    163. params: {
    164. xmlnsOrder: "alphabetical",
    165. },
    166. },
    167. ],
    168. },
    169. ],
    170. ],
    171. },
    172. },
    173. }),
    174. ],
    175. splitChunks: {
    176. chunks: "all",
    177. },
    178. runtimeChunk: {
    179. name: (entrypoint) => `runtime~${entrypoint.name}`,
    180. },
    181. },
    182. resolve: {
    183. extensions: [".vue", ".js", ".json"],
    184. },
    185. devServer: {
    186. open: true,
    187. host: "localhost",
    188. port: 3000,
    189. hot: true,
    190. compress: true,
    191. historyApiFallback: true, // 解决vue-router刷新404问题
    192. },
    193. mode: isProduction ? "production" : "development",
    194. devtool: isProduction ? "source-map" : "cheap-module-source-map",
    195. };

    vue的全家桶配置

    vue-router

    npm i vue-router


    在src文件下创建一个 router 文件夹,里边创建一个index.js

    1. import { createRouter,createWebHistory } from 'vue-router'
    2. import index from './components/index.vue'
    3. import login from './components/login.vue'
    4. const routerHistory = createWebHistory()
    5. const routes = [
    6. {
    7. path:'/',
    8. name:'index',
    9. component:index
    10. },
    11. {
    12. path:'/login',
    13. name:'login',
    14. component:login
    15. }
    16. ]
    17. const router = createRouter({
    18. history: routerHistory,
    19. routes
    20. })
    21. export default router



    在main.js中引入router

    1. import { createApp } from 'vue'
    2. import App from './App.vue'
    3. import router from './router'
    4. import './index.css'
    5. const app = createApp(App);
    6. app.use(router);
    7. app.mount('#app')


    vuex


    安装 vuex

    npm i vuex


    在src文件下创建一个 store 文件夹,里边创建一个index.js

    1. // 准备引入 vuex
    2. import { createStore } from 'vuex'
    3. const store = createStore({
    4. // state:{},
    5. state(){},
    6. mutations:{},
    7. getters:{},
    8. actions:{},
    9. modules:{}
    10. })
    11. export default store


    在main.js中引入veux

    1. import { createApp } from 'vue'
    2. import App from './App.vue'
    3. import router from './router'
    4. // 挂载
    5. createApp(App).use(router).mount('#app')
  • 相关阅读:
    [CSS]浮动
    Fedora Linux 38 下可以安装几个数学软件
    vcluster -- 基于虚拟集群的多租户方案
    [机缘参悟-73]:深度思考:心智提升的七个阶段
    算法篇:查找算法
    C++ map / multimap容器
    pytest合集(7)— 参数化/数据驱动
    基于SSM的餐厅点餐系统设计与实现(Java+MySQL)
    xlsxStyle + xlsx.full.min 导出数据,并设置导出样式
    C#基础入门教程-数据类型
  • 原文地址:https://blog.csdn.net/qq_60587956/article/details/126808303