搭建 Vue3.x 项目工程环境

53 阅读5分钟

搭建 Vue3.x 项目工程环境

技术栈

项目搭建

确保电脑上成功安装 node 及相关环境

node -v
v22.8.0

npm -v
10.8.3

* 通过 npm 安装 pnpm ( npm install pnpm -g )
pnpm -v
9.11.0

使用 Vite 初始化项目

1. 使用 vite 搭建项目(项目名称:my-vue-app)
pnpm create vite my-vue-app
2. 选择框架
? Select a framework: » - Use arrow-keys. Return to submit.
    Vani11a
>   Vue
    React
    Preact
    Lit
    Svelte
    solid
    Qwik
    Others

这里选择 Vue
✓ Select a framework: » Vue
3. 选择语言
? Select a variant: » - Use arrow-keys. Return to submit.
>   TypeScript
    JavaScript
    Customize with create-vue
    Nuxt

这里选择 TypeScript
✓ Select a variant: » TypeScript
4. 安装依赖
pnpm install
5. 启动项目
pnpm run dev
6. 规范目录结构
├── config/
    ├── plugin/
    ├── vite.config.base.ts        // Vite 基础配置
    ├── vite.config.dev.ts         // Vite 开发配置
    ├── vite.config.prod.ts        // Vite 正式配置
├── piblic/
└── src/
    ├── assets/                    // 静态资源目录
        ├── images/                // 图片资源目录
        ├── style/                 // 通用样式目录
    ├── components/                // 公共组件目录
    ├── router/                    // 路由配置目录
    ├── store/                     // 状态管理目录
    ├── utils/                     // 工具函数目录
    ├── views/                     // 页面组件目录
    ├── App.vue
    ├── main.ts
    ├── vite-env.d.ts
├── index.html
├── tsconfig.app.json              // TypeScript 配置文件
├── tsconfig.json                  // TypeScript 配置文件
├── tsconfig.node.json             // TypeScript 配置文件
├── vite.config.ts                 // Vite 配置文件
└── package.json
7. 修改 Vite 配置文件

在根目录下创建 config 目录,然后在 config 目录中新建 vite.config.base.ts、vite.config.dev.ts 文件,并执行以下命令

pnpm i @types/node @vitejs/plugin-legacy vite-svg-loader -D

vite.config.base.ts

import { defineConfig } from 'vite';
import { resolve } from 'path';
import vue from '@vitejs/plugin-vue';
import legacy from '@vitejs/plugin-legacy';
import svgLoader from 'vite-svg-loader';

export default defineConfig({
  plugins: [
    vue(),
    svgLoader({ svgoConfig: {} }),
    legacy({
      targets: ['defaults', 'not IE 11'],
    }),
  ],
  resolve: {
    alias: [
      {
        find: '@',
        replacement: resolve(__dirname, '../src'),
      },
      {
        find: 'assets',
        replacement: resolve(__dirname, '../src/assets'),
      },
      {
        find: 'vue',
        replacement: 'vue/dist/vue.esm-bundler.js',
      },
    ],
    extensions: ['.ts', '.js'],
  },
  define: {
    'process.env': {},
  },
});

vite.config.dev.ts

import { mergeConfig } from 'vite';
import baseConfig from './vite.config.base';

export default mergeConfig(
  {
    mode: 'development',
    server: {
      open: true,
      fs: {
        strict: true,
      },
    },
    plugins: [],
  },
  baseConfig,
);

删除根目录下的 vite.config.ts 文件,然后修改根目录下的 package.json 文件

package.json

"scripts": {
  "dev": "vite --config ./config/vite.config.dev.ts",
  "build": "vue-tsc -b && vite build",
  "preview": "vite preview"
}

集成路由工具 Vue Router

1. 安装路由工具 vue-router
pnpm i vue-router@4 nprogress

pnpm i @types/nprogress -D
2. 创建配置文件

在 src 目录下创建 router 目录,然后在 router 目录里新建 index.ts、typing.d.ts 文件

index.ts

import { createRouter, createWebHashHistory } from 'vue-router';
import * as NProgress from 'nprogress';
import 'nprogress/nprogress.css';

NProgress.configure({ showSpinner: false });

const router = createRouter({
  history: createWebHashHistory(),
  routes: [],
  scrollBehavior() {
    return { top: 0 };
  },
});

export default router;

typing.d.ts

import 'vue-router';

declare module 'vue-router' {
  interface RouteMeta {
    roles?: string[];
    requiresAuth: boolean;
    icon?: string;
    locale?: string;
    hideInMenu?: boolean;
    hideChildrenInMenu?: boolean;
    activeMenu?: string;
    order?: number;
    noAffix?: boolean;
    ignoreCache?: boolean;
  }
}
3. 挂载路由配置

main.ts

import { createApp } from 'vue';
import router from '@/router/index';
import App from './App.vue';

const app = createApp(App);

app.use(router);

app.mount('#app');

集成状态管理工具 Pinia

1. 安装状态管理工具 Pinia
pnpm i pinia
2. 创建配置文件

在 src 目录下创建 store 目录,然后在 store 目录里新建 modules 目录 和 index.ts 文件

index.ts

import { createPinia } from 'pinia';

const pinia = createPinia();

export {};
export default pinia;
3. 挂载 Pinia 配置

main.ts

import { createApp } from 'vue';
import store from '@/store/index';
import App from './App.vue';

const app = createApp(App);

app.use(store);

app.mount('#app');

集成 UI 框架 Arco Design

1. 安装 UI 框架 Arco Design
pnpm i @arco-design/web-vue @vueuse/core

pnpm i unplugin-vue-components -D
2. 挂载 Arco Design

main.ts

import { createApp } from 'vue';
import ArcoVue from '@arco-design/web-vue/es/arco-vue';
import ArcoVueIcon from '@arco-design/web-vue/es/icon/arco-vue-icon';
import App from './App.vue';
import '@arco-design/web-vue/dist/arco.css';

const app = createApp(App);

app.use(ArcoVue, {});
app.use(ArcoVueIcon);

app.mount('#app');
3. 修改 Vite 配置文件

在 config 目录中新建 plugin 目录 和 vite.config.prod.ts 文件,然后在 plugin 目录中新建 arcoResolver 文件

arcoResolver.ts

import Components from 'unplugin-vue-components/vite';
import { ArcoResolver } from 'unplugin-vue-components/resolvers';

export default function configArcoResolverPlugin() {
  const arcoResolverPlugin = Components({
    dirs: [],
    deep: false,
    resolvers: [ArcoResolver()],
  });
  return arcoResolverPlugin;
}

vite.config.prod.ts

import { mergeConfig } from 'vite';
import baseConfig from './vite.config.base';
import configArcoResolverPlugin from './plugin/arcoResolver';

export default mergeConfig(
  {
    mode: 'production',
    plugins: [configArcoResolverPlugin()],
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            arco: ['@arco-design/web-vue'],
            vue: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
          },
        },
      },
      chunkSizeWarningLimit: 2000,
    },
  },
  baseConfig,
);

修改根目录下的 package.json 文件

package.json

"scripts": {
  "dev": "vite --config ./config/vite.config.dev.ts",
  "build": "vue-tsc -b && vite build --config ./config/vite.config.prod.ts",
  "preview": "vite preview"
}

集成 HTTP 工具 Axios

代码规范

集成 Prettier 配置

1. 安装 Prettier 工具
pnpm i prettier -D
2. 创建 .prettierignore、.prettierrc 文件

.prettierignore

/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

.prettierrc

{
  "tabWidth": 2,
  "semi": true,
  "printWidth": 80,
  "singleQuote": true,
  "quoteProps": "consistent",
  "htmlWhitespaceSensitivity": "strict",
  "vueIndentScriptAndStyle": true,
  "endOfLine": "crlf"
}
3. 使用 Prettier 格式化代码
pnpm exec prettier . --write

集成 ESLint 配置

1. 安装 ESLint 工具
pnpm create @eslint/config@latest
2. 选择 ESLint 配置

你想如何使用 ESLint? >> 检查语法、发现问题

? How would you like to use ESLint? ...
  To check syntax only
> To check syntax and find problems

这里选择 To check syntax and find problems
√ How would you like to use ESLint? · problems

你的项目使用哪种类型的模块?

? What type of modules does your project use? ...
> JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

这里选择 JavaScript modules (import/export)
√ What type of modules does your project use? · esm

你的项目使用哪种框架?

? Which framework does your project use? ...
  React
> Vue.js
  None of these

这里选择 Vue.js
√ Which framework does your project use? · vue

你的项目是否使用 TypeScript ?

? Does your project use TypeScript? ...
  No
> Yes

这里选择 Yes
 Does your project use TypeScript? · typescript

你的代码在哪里运行?

? Where does your code run? ...  (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
√ Node

这里选择 Browser、Node(按空格键进行选择,选完按回车键确定)
√ Where does your code run? · browser, node

你想现在就安装它们吗?

? Would you like to install them now? » No / Yes

这里选择 Yes

你想使用哪一个管理工具?

? Which package manager do you want to use? ...
  npm
  yarn
> pnpm
  bun
3. 修改配置文件 eslint.config.js

eslint.config.js

import globals from 'globals';
import pluginJs from '@eslint/js';
import tseslint from 'typescript-eslint';
import pluginVue from 'eslint-plugin-vue';

export default [
  {
    files: ['**/*.{js,mjs,cjs,ts,vue}'],
  },
  {
    languageOptions: {
      globals: {
        ...globals.browser,
        ...globals.node,
      },
    },
  },
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  ...pluginVue.configs['flat/essential'],
  {
    files: ['**/*.vue'],
    languageOptions: {
      parserOptions: {
        parser: tseslint.parser,
      },
    },
  },
  {
    rules: {},
  },
];

集成 StyleLint 配置

解决 Prettier 和 ESLint、StyleLint 的冲突

1. 解决 Prettier 和 ESLint 的冲突

安装 eslint-config-prettier

 pnpm i eslint-config-prettier  -D

修改配置文件 eslint.config.js

eslint.config.js

...
import someConfig from 'some-other-config-you-use';
import eslintConfigPrettier from 'eslint-config-prettier';

export default [
  ...
  someConfig,
  eslintConfigPrettier,
];