前端工程化
[toc]
dotenv-cli: 或者使用dotenv-cli
import.meta元数据
import.meta返回当前模块的元信息。
import.meta只能在模块内部使用,如果在模块外部使用会报错。
主要信息:
-
import.meta.url:当前页面的url.
-
import.meta.dev:是否是开发环境.
-
import.meta.env:一些环境变量.
-
DEV:是否开发环境.
-
PROD:是否生产环境.
-
MODE:什么模式.字符串.
-
SSR:是否服务端模式.
-
VITE_XXX:自定义变量.
-
BASE_URL:基本地址.
-
.env文件配置全局环境变量
文件说明:
.env:全局默认配置文件,无论什么环境都会加载合并。
.env.development:开发环境的配置文件
.env.production:生产环境的配置文件
并且在.env文件中变量名要以 VITE_ 开头(vite环境下) 好像NUXT_开头不行[NUXT_ 开头 (nuxt环境下)],且变量名全部大写.
Vite 会根据启动命令中( --mode )自动加载相对应的环境配置文件:
- 例如,当你启动 npm run dev时,就会自动加载
.env.development - 当你进行打包准备发布到生产,npm run build, 然后 npm run preview 进行生产预览,vite就会自动加载
.env.production
这个mode是需要在 package.json script中配置好的.
! 当全局的配置文件和环境的配置文件有相同配置项时,环境的配置项会覆盖全局的配置项
项目中可以通过 import.meta.env.XXX 来访问你配置的环境变量.
vite-vue3工程化
目录:
- 配置别名
- vue-router
- Pinia
- ESlint
- Prettier
- Husky 与 Lint-staged
- git cz
- AutoImport
- Tailwindcss
- 其他[@vueuse/core.. loadesh.. ]
- Vite 打包配置 Server配置
- 配置生产环境与开发环境
- 封装请求函数
- 附录
-
创建vite-vue3项目: 通过webstrom.
-
配置别名
-
实现可以通过 @/view/xxx.vue 的方式去书写文件路径.
-
vite.config.ts:import { defineConfig } from "vite"; //如果遇到path这一行报错,需要安装node类型: pnpm i -D @types/node import * as path from "path"; export default defineConfig({ ... resolve: { //设置别名 alias: { "@": path.resolve(__dirname, "src"), }, }, }); -
tsconfig.ts:... "compilerOptions": { ... /** 路径别名 */ "baseUrl": "./", "paths": { "@": ["src"], "@/*": ["src/*"] }, } ... "exclude": ["node_modules"],
-
-
vue-router :
-
安装: pnpm i vue-router@4;
-
使用:
Main.ts:... import router from "./router"; createApp(App).use(router).mount('#app')
-
-
Pinia :
-
安装 : pnpm i pinia;
-
使用:
main.ts:... import { createPinia } from 'pinia' createApp(App).use(createPinia()).mount('#app');
-
-
ESlint:
-
安装: pnpm i eslint --save-dev;
-
初始化: pnpm eslint --init;
-
配置: 在
package.json中,配置 ESLint 脚本指令;package.json:... "scripts": { ... "eslint": "eslint src --ext .js,.vue,.ts,.jsx,.tsx --ignore-path .gitignore --fix", } -
安装解析vue的eslint插件: pnpm i eslint-plugin-vue --save-dev;
- 修改
.eslintrc.json文件... // 添加 vue文件解析器 解析template文件 "parser": "vue-eslint-parser", "parserOptions": { ... }
- 修改
-
配置项目启动/打包实时校验代码: pnpm i vite-plugin-eslint --save-dev;
-
修改
vite.config.ts文件... import eslintPlugin from "vite-plugin-eslint"; //导入包 ... // 配置ESLint插件 plugins: [vue(), eslintPlugin()], -
在webstrom上设置 保存时自动运行.
-
-
-
Prettier:
-
安装: pnpm i --save-dev prettier
-
创建配置文件
.prettierrc.cjs:module.exports = { // 一行最多多少个字符 printWidth: 150, // 指定每个缩进级别的空格数 tabWidth: 2, // 使用制表符而不是空格缩进行 useTabs: false, // 在语句末尾是否需要分号 semi: false, // 是否使用单引号 singleQuote: true, // 更改引用对象属性的时间 可选值"<as-needed|consistent|preserve>" quoteProps: "as-needed", // 在JSX中使用单引号而不是双引号 jsxSingleQuote: false, // 多行时尽可能打印尾随逗号。(例如,单行数组永远不会出现逗号结尾。) 可选值"<none|es5|all>",默认none trailingComma: "es5", // 在对象文字中的括号之间打印空格 bracketSpacing: true, // jsx 标签的反尖括号需要换行 jsxBracketSameLine: false, // 在单独的箭头函数参数周围包括括号 always:(x) => x \ avoid:x => x arrowParens: "always", // 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码 rangeStart: 0, rangeEnd: Infinity, // 指定要使用的解析器,不需要写文件开头的 @prettier requirePragma: false, // 不需要自动在文件开头插入 @prettier insertPragma: false, // 使用默认的折行标准 always\never\preserve proseWrap: "preserve", // 指定HTML文件的全局空格敏感度 css\strict\ignore htmlWhitespaceSensitivity: "css", // Vue文件脚本和样式标签缩进 vueIndentScriptAndStyle: false, //在 windows 操作系统中换行符通常是回车 (CR) 加换行分隔符 (LF),也就是回车换行(CRLF), //然而在 Linux 和 Unix 中只使用简单的换行分隔符 (LF)。 //对应的控制字符为 "\n" (LF) 和 "\r\n"(CRLF)。auto意为保持现有的行尾 // 换行符使用 lf 结尾是 可选值"<auto|lf|crlf|cr>" endOfLine: "auto", }; -
配置package.json文件:
... "prettier": "prettier --write \"./**/*.{html,vue,ts,js,json,md}\"" -
处理prettier 与 ESLint 的配置冲突:
-
安装处理配置冲突文件: pnpm i --save-dev eslint-config-prettier pnpm i --save-dev eslint-plugin-prettier
-
配置 ESLint 配置文件
.eslintrc.json:... "extends":[ ... // 告诉 ESLint 关闭与 Prettier 格式化规则冲突的任何规则,需写在最后,会覆盖前面的配置 "plugin:prettier/recommended" ], ... "plugins": [ ... // 将 Prettier 的格式化功能集成到 ESLint 中。会应用Prettier的配置 "prettier" ],
-
-
-
Husky 与 Lint-staged
前提:需要是git项目.
-
安装: pnpm install husky lint-staged --save-dev
-
生成文件: npx husky install
-
生成 git hook: npx husky add .husky/pre-commit 'npx lint-staged'
-
在
package.json中配置 lint-staged:"lint-staged": { "src/**/*.{ts,js,jsx,tsx,vue}": [ "eslint --fix", "prettier --write" ] }
-
-
git cz
-
全局安装commitizen: pnpm install -g commitizen
-
安装cz-git : pnpm install -D cz-git
-
修改
packge.json添加config指定使用的适配器:... "config": { "commitizen": { "path": "node_modules/cz-git" } }
-
-
AutoImport
-
安装 : pnpm i -D unplugin-auto-import pnpm i -D unplugin-vue-components
-
在
vite.config.ts中配置:import AutoImport from 'unplugin-auto-import/vite'; import Components from 'unplugin-vue-components/vite'; ... //如果安装了ElementUI或者其他UI组件使用此. import { ElementPlusResolver, AntDesignVueResolver} from 'unplugin-vue-components/resolvers' plugins: [ vue(), AutoImport({ // 可以自定义文件生成的位置,默认是根目录下,使用ts的建议放src目录下 imports: ["vue", "vue-router", "@vueuse/core", "pinia"], dts: true, // 根据引入来源自动生成的类型声明文件路径 eslintrc: { enabled: true // 使用 eslint 配置 } }), Components({ dts: true, // 根据引入来源自动生成的类型声明文件路径 dirs: ['src/components'], // 按需加载的文件夹 ////如果安装了ElementUI或者其他UI组件使用此. resolvers: [ ElementPlusResolver(), // Antd 按需加载 AntDesignVueResolver() // ElementPlus按需加载 ] }) ], -
在
.eslintrc.json文件中配置:extends: [ "./.eslintrc-auto-import.json", ],
-
-
Tailwindcss
-
安装: pnpm i -D tailwindcss@latest
-
创建tailwindcss的配置文件: npx tailwindcss init
-
tailwind.config.js文件配置:
... content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],-
vite.config.ts文件配置:import tailwindcss from 'tailwindcss'; ... css: { postcss: { plugins: [tailwindcss], }, }, -
style.css中重写并在main.ts中导入:@tailwind base; @tailwind components; @tailwind utilities;
-
Vite 打包配置 Server配置
打包配置:
vite.config.ts:
... build: { //输出目录 outDir: "./dist", //构建后是否输出sourcemap sourcemap: true, },
Server配置:
vite.config.ts:
... server: { ////指定服务器应该监听哪个 IP 地址。 host:"localhost", //指定开发端口 port:5573, //设置代理 proxy: { //普通代理 '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, //代理socket '/socket.io': { target: 'ws://localhost:5174', ws: true, }, }, //设置跨域,允许任意源 cors:true, }
vite 配置生产环境与开发环境
-
创建生产环境和开发环境模式文件: .env.dev / .env.prod
-
在这两个文件中,以VITE_开头的变量可以透传到客户端,客户端(vite配置)中可以取到,以其他开头的是私有变量,仅vite server可以获取得到.
-
在package.json中增加对应的启动命令即可让Vite获取哪个模式来运行项目
package.json:"scripts": { "dev" :"vite --mode dev", "prod": "vite --mode prod", "build:dev": "vite build --mode dev", "build:prod": "vite build --mode prod", } -
然后就可以在刚才新建的两个模式文件中各自写对应模式的变量. 例如:
.env.dev中:ENV = 'development' VITE_APP_API_HOST = 'http://localhost:8888' VITE_APP_PROXY_API = 'http://172.16.23.147' VITE_APP_ROUTER_PREFIX = '/' ... -
在vite.config.ts中再进行配置
!注意: Vite 默认是不加载 .env 文件的,因为这些文件需要在执行完 Vite 配置后才能确定加载哪一个,举个例子,root 和 envDir 选项会影响加载行为。不过当你的确需要时,你可以使用 Vite 导出的 loadEnv 函数来加载指定的.env 文件.
import { defineConfig, loadEnv,type ConfigEnv } from 'vite' export default defineConfig(({mode,command}:ConfigEnv) => { //获取当前vite运行环境 const env = loadEnv(mode, process.cwd()); //然后,再将原来的config 进行return出去,但是里面的属性可以根据env进行变化了. return { base:..., plugins:[...], resolve:{...}, build:{...}, server:{...}, } }) -
如果想在除了vite.config.ts中使用环境变量(比如自己封装axios时),可以通过 import.meta.env. 进行获得.
附录:[所有配置文件]
vite.config.ts:
import { defineConfig, loadEnv } from 'vite'; import vue from '@vitejs/plugin-vue'; import * as path from 'path'; import eslintPlugin from 'vite-plugin-eslint'; import AutoImport from 'unplugin-auto-import/vite'; import Components from 'unplugin-vue-components/vite'; import tailwindcss from 'tailwindcss'; export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd()); return { base: env.VITE_APP_ROUTER_PREFIX, plugins: [ vue(), eslintPlugin(), AutoImport({ dts: true, imports: ['vue', 'vue-router', '@vueuse/core', 'pinia'], eslintrc: { enabled: true, }, }), Components({ dts: true, dirs: ['src/components'], resolvers: [], }), ], resolve: { alias: { '@': path.resolve(__dirname, 'src'), }, }, css: { postcss: { plugins: [tailwindcss], }, }, build: { outDir: env.VITE_APP_OUTPUT, sourcemap: Boolean(env.VITE_APP_SOURCEMAP), }, server: { host: 'localhost', port: 5588, proxy: { '/api': { target: env.VITE_APP_PROXY_API, changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, }, cors: true, }, }; });
tsconfig.json:
{ "extends": "@vue/tsconfig/tsconfig.dom.json", "compilerOptions": { "allowJs": true, "paths": { "@/*": ["./src/*"] }, "outDir": "./dist" }, "include": ["./*.d.ts", "./src/**/*.ts", "./src/**/*.vue"] }
tailwind.config.js:
/** @type {import('tailwindcss').Config} */ export default { content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], theme: { extend: {}, }, plugins: [], };
package.json:
... "scripts": { "dev": "vite --mode dev", "prod": "vite --mode prod", "build:dev": "vite build --mode dev", "build:prod": "vite build --mode prod", "preview": "vite preview", "eslint": "eslint src --ext .js,.vue,.ts,.jsx,.tsx --ignore-path .gitignore --fix", "prettier": "prettier --write \"./**/*.{html,vue,ts,js,json,md}\"" }, "lint-staged": { "src/**/*.{ts,js,jsx,tsx,vue}": [ "eslint --fix", "prettier --write" ] }, "config": { "commitizen": { "path": "node_modules/cz-git" } } ...
.prettierrc.cjs:
module.exports = { // 一行最多多少个字符 printWidth: 150, // 指定每个缩进级别的空格数 tabWidth: 2, // 使用制表符而不是空格缩进行 useTabs: false, // 在语句末尾是否需要分号 semi: true, // 是否使用单引号 singleQuote: true, // 更改引用对象属性的时间 可选值"<as-needed|consistent|preserve>" quoteProps: "as-needed", // 在JSX中使用单引号而不是双引号 jsxSingleQuote: false, // 多行时尽可能打印尾随逗号。(例如,单行数组永远不会出现逗号结尾。) 可选值"<none|es5|all>",默认none trailingComma: "es5", // 在对象文字中的括号之间打印空格 bracketSpacing: true, // jsx 标签的反尖括号需要换行 jsxBracketSameLine: false, // 在单独的箭头函数参数周围包括括号 always:(x) => x \ avoid:x => x arrowParens: "always", // 这两个选项可用于格式化以给定字符偏移量(分别包括和不包括)开始和结束的代码 rangeStart: 0, rangeEnd: Infinity, // 指定要使用的解析器,不需要写文件开头的 @prettier requirePragma: false, // 不需要自动在文件开头插入 @prettier insertPragma: false, // 使用默认的折行标准 always\never\preserve proseWrap: "preserve", // 指定HTML文件的全局空格敏感度 css\strict\ignore htmlWhitespaceSensitivity: "css", // Vue文件脚本和样式标签缩进 vueIndentScriptAndStyle: false, //在 windows 操作系统中换行符通常是回车 (CR) 加换行分隔符 (LF),也就是回车换行(CRLF), //然而在 Linux 和 Unix 中只使用简单的换行分隔符 (LF)。 //对应的控制字符为 "\n" (LF) 和 "\r\n"(CRLF)。auto意为保持现有的行尾 // 换行符使用 lf 结尾是 可选值"<auto|lf|crlf|cr>" endOfLine: "auto", };
.eslintrc-auto-import.json:
自动生成.
.eslintrc.json:
{ "env": { "browser": true, "es2021": true, "node": true }, "extends": [ "./.eslintrc-auto-import.json", "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:vue/vue3-essential", // 告诉 ESLint 关闭与 Prettier 格式化规则冲突的任何规则,需写在最后,会覆盖前面的配置 "plugin:prettier/recommended" ], // 添加 vue文件解析器 解析template文件 "parser": "vue-eslint-parser", "parserOptions": { "ecmaVersion": "latest", "parser": "@typescript-eslint/parser", "sourceType": "module" }, "plugins": [ "@typescript-eslint", "vue", // 将 Prettier 的格式化功能集成到 ESLint 中。会应用Prettier的配置 "prettier" ], "rules": { } }
.env.dev .env.prod ...