# vue3-vite
**Repository Path**: hboot/vue3-vite
## Basic Information
- **Project Name**: vue3-vite
- **Description**: vite配置vue3开发环境 ,实际项目配置,vite.config.js; vue-router、vuex
- **Primary Language**: JavaScript
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 14
- **Forks**: 3
- **Created**: 2022-04-05
- **Last Updated**: 2025-05-12
## Categories & Tags
**Categories**: Uncategorized
**Tags**: vite, vue3
## README
vite + vue3
安装 vite 从 0 搭建 vue3 开发环境。
### 安装 `vite`
支持 vue 模板文件,支持`jsx`语法文件
```sh
npm install vite
```
> 安装 `@vitejs/plugin-vue-jsx ` `@vitejs/plugin-vue`
```js
// 类型提示
import { defineConfig } from "vite";
import vueJSX from "@vitejs/plugin-vue-jsx";
import vueSFC from "@vitejs/plugin-vue";
// config
export default defineConfig(({ command, mode }) => {
/**
* command - 命令模式
* mode - 生产、开发模式
*/
return {
// 项目根目录,index.html 所在的目录
root: "",
// 生产或开发环境下的基础路径
base: "/",
// 需要用到的插件数组
plugins: [
// .vue 单文件组件
vueSFC(),
// .jsx 文件类型支持
vueJSX({
// ... @vue/babel-plugin-jsx 的配置
}),
],
// 静态资源服务目录地址
publicDir: "",
// 存储缓存文件的目录地址
cacheDir: "",
//
resolve: {
// 设置文件目录别名
alias: {
"@": "/src",
},
//
extensions: [".js", ".jsx", ".vue"],
},
//
css: {
// postcss-modules 行为配置
modules: {
// ...
},
// 传递给css预处理器的配置项
preprocessorOptions: {
// 指定less预处理的配置项
less: {
// ...
},
},
},
// esbuild 选项转换配置
esbuild: {
// ...
// 在react组件中无需导入react
// jsxInject: `import React from 'react'`,
// vue 使用jsx
jsxFactory: "h",
jsxFragment: "Fragment",
},
// 静态资源处理
assetsInclude: "",
// 开发服务器选项
server: {
// ...
host: "127.0.0.1",
port: "8081",
// 项目启动后自动打开浏览器
open: true,
},
// 构建配置项
build: {
// ...
// 指定输出目录
outDir: "./dist",
// 指定静态资源存放目录
assetsDir: "",
// 启用、禁用css代码拆分
cssCodeSplit: true,
// 构建是否生成source map文件
sourcemap: "inline",
// rollup 配置打包项
rollupOptions: {
// ...
// input:"src/index.js"
},
// 构建目录自动清除
emptyOutDir: false,
},
// 依赖优化配置项
optimizeDeps: {
// 依赖构建入口
entries: "",
// 排除不需要构建的依赖项
exclude: [],
},
};
});
```
### 支持 vue 开发
#### 安装`@vitejs/plugin-vue`
SFC 单文件组件`.vue`
```vue
```
可查看示例`ElementPlus/index.vue`
#### 安装`@vitejs/plugin-vue-jsx`
支持 JSX 语法
```jsx
import { defineComponent } from "vue";
export default defineComponent({
data() {
return {};
},
render() {
return <>>;
},
});
```
### 安装 `vue-router`
### 安装 `vuex` , 改用了 `pinia`
项目中可同时存在,这是示例项目。在实际项目开发中,还需要确定一种,避免数据状态来源不明。造成的代码阅读困扰
```shell
npm install pinia
```
在每个模块中,按目录创建,不需要导入到全局 store 对象中。
在`setup` 或者 JSX 响应式模式中,使用
```js
import { uesSystemStore } from "@/store/system.js";
import { computed } from "vue";
// ... other
export default defineComponent({
setup(props, context) {
// 获取到pinia的数据
const systemStore = uesSystemStore();
// 计算值
const name = computed(() => systemStore.systemName);
return {
name,
systemStore,
};
},
});
```
在传统的`.vue`模板中
```js
import { useTabStore } from "../../model";
export default {
data() {
// 此处可创建store实例
this.tabStore = useTabStore();
return {
// list data
data: [],
};
},
computed: {
activeTab() {
return this.tabStore.activeTab;
},
},
};
```
### 安装 `element-plus`
全局配置
```js
// element
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import { zhCn } from "element-plus/es/locale/index.js";
// ....
// element 国际化设置
app.use(ElementPlus, { size: "small", zIndex: 3000, local: zhCn });
```
### 安装 `axios`
### 安装 `dayjs`
### markdown 支持
安装`markdown-it` `highlight.js`
使用: 代码是写在`setup`中的
```js
// markdown
import MarkdownIt from "markdown-it";
import hljs from "highlight.js";
// 将README.md导入进来
import ReadME from "/README.md?raw";
// 生命周期,挂载
onMounted(() => {
// 加载README.md
const md = new MarkdownIt({
html: false, // Enable HTML tags in source
xhtmlOut: false, // Use '/' to close single tags (
).
// This is only for full CommonMark compatibility.
breaks: false, // Convert '\n' in paragraphs into
langPrefix: "language-", // CSS language prefix for fenced blocks. Can be
// useful for external highlighters.
linkify: false, // Autoconvert URL-like text to links
// Enable some language-neutral replacement + quotes beautification
// For the full list of replacements, see https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js
typographer: false,
// Double + single quotes replacement pairs, when typographer enabled,
// and smartquotes on. Could be either a String or an Array.
//
// For example, you can use '«»„“' for Russian, '„“‚‘' for German,
// and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
quotes: "“”‘’",
highlight: (str, lang) => {
if (lang && hljs.getLanguage(lang)) {
try {
return (
'
' +
hljs.highlight(str, {
language: lang,
ignoreIllegals: true,
}).value +
"
"
);
} catch (__) {}
}
return (
'' + md.utils.escapeHtml(str) + "
"
);
},
});
// llink
md.linkify.set({ fuzzyEmail: false });
content.value = md.render(ReadME);
});
```
加载个样式,有很多可供挑选 在`import "highlight.js/styles/atom-one-dark.css"`
试了好几个,最后选择了这个,看着还不错。

#### 安装`markdown-it-anchor` 以便更好的导航
```sh
npm install markdown-it-anchor @sindresorhus/slugify
```
#### 安装`node-html-parser` 解析字符串为 html
```sh
npm install node-html-parser
```
### 安装`eslint\husky` 代码规范
代码规范;统一代码格式校验; (有一些配置还是有问题)
eslint 配置文件 `.eslintrc.js`
prettier 配置文件`.prettierrc.js`
#### `eslint` 代码格式校验
- `eslint-config-standard`
- `eslint-plugin-import`
- `eslint-plugin-node`
- `eslint-plugin-promise`
#### `prettier` 配合校验,格式化代码文件
vscode 安装`Prettier - Code formatter`, 设置配置;`format on save` and `formatter`
安装`eslint-config-prettier` 处理 eslint 和 prettier 之间的冲突;
支持`vue` 语法检测
`eslint-plugin-vue`
配置`.eslintrc.js`:
```js
module.exports = {
extends: ["standard", "plugin:vue/vue3-recommended", "prettier"],
};
```
#### `husky` git hooks 管理
安装
```sh
npm install husky --save-dev
```
在项目初始化时,需要执行`npm set-script prepare "husky install"`
初始化一个在 git commit 之前进行 eslint 的钩子。
```sh
npx husky add .husky/pre-commit "npm run lint"
//
git add .husky/pre-commit
```
#### lint-staged 检测缓存区的改动文件
```sh
npm install --save-dev lint-staged
```
修改 hook `pre-commit`
```
npm run lint-staged
```
### i18n 国际化配置
安装插件
```sh
//
npm i --save-dev vue-i18n
// vite 插件,暂时没有用到
npm i --save-dev @intlify/vite-plugin-vue-i18n
```
配置`index.js`
```js
// vue-i18n
import { createI18n } from "vue-i18n";
// locale
import enLocale from "./locals/en.json";
import cnLocale from "./locals/cn.json";
// 4. 国际化配置
const i18n = createI18n({
locale: "zh",
messages: {
en: {
...en,
...enLocale,
},
zh: {
...zhCn,
...cnLocale,
},
},
});
// 国际化
app.use(i18n);
```
### 文件预览,pdf、docx、pptx
除了 pdf,其他文件都是可编辑的,所以里面的内容可能会由于转换丢失样式等。计划想先把其他文件转成 pdf 然后在预览。
#### `.pdf`预览
安装`pdfjs-dist`
```sh
npm install pdfjs-dist --save
```
由于 vite 没有 require 模块,导致不能使用。在 issue 中找到了替代
重新安装,
```sh
# 支持es module
npm install @bundled-es-modules/pdfjs-dist
```
#### `.docx`预览
```sh
npm install mammoth
```
### `polyfills` 有使用 node 核心库 API 的依赖
```sh
$> npm i vite-plugin-node-polyfills
```
在`vite.config.js`增加配置
### `Element-plus`按需加载,无需全量
移除掉`/src/index.js`里的 Element-plus 导入
安装依赖
```sh
$> npm i unplugin-auto-import unplugin-vue-components --save-dev
```
增加配置`vite.config.js`.
> 使用了`.jsx`文件作为页面组件,不能生效,`.vue`单位件下是可以的,所以选择其中之一的方式进行书写。
全局注册和按需加载不能同时使用,避免造成冲突。
### Blog -系列文章
[vite-vue3 开发环境搭建](https://juejin.cn/post/7121174783407947783)
[Vue3 现在有多少种写法?](https://juejin.cn/post/7123482857632169997)
[vue3 sfc 单文件组件中如何书写 JSX 语法?](https://blog.csdn.net/heroboyluck/article/details/126057882?spm=1001.2014.3001.5501)
[vite 配置多页面应用](https://juejin.cn/post/7139101096810643492)
[pdf、markdown、docx 文件预览](https://blog.csdn.net/heroboyluck/article/details/127502521?spm=1001.2014.3001.5502)
### QA 问题记录
1. `$router.push()` 后,在点击`/` 跳转路由不对
2. 选择器,模糊匹配,比如`h1-h6` 可通过`h[1-6]`进行匹配
3. CSS 选择器附加父元素或上一个兄弟元素条件
4. 使用 a 标签进行导航 md 时,地址会映射到 hash 路由上
5. 使用 vs code 提交同步更改时,没有执行 git hooks
6. 依赖更新,移除掉`package.json`相关依赖,重新安装
主要依赖:
```sh
$> npm i vue vite @vitejs/plugin-vue @vitejs/plugin-vue-jsx axios dayjs element-plus pinia vue-router vuex vue-i18n
```
`--save-dev`依赖
```sh
$> npm i eslint eslint-config-prettier eslint-config-standard eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-vue husky less lint-staged
```