返回

从零搭建Vue3+TypeScript+Vite项目

前端

使用 Vite 构建 Vue3 + TypeScript 项目并配置多语言版本

项目搭建

使用 Vite 构建 Vue3 + TypeScript 项目是一个简单的过程。首先,确保已安装 Node.js 和 npm。然后,创建一个项目目录并安装 Vite:

npm install vite --save-dev

接下来,使用以下命令初始化 Vue3 项目:

npm init -y
npm install vue@next vue-router@next --save

对于 TypeScript,还需要安装以下依赖项:

npm install typescript @vitejs/plugin-vue --save-dev

创建 tsconfig.json 文件并添加以下内容:

{
  "compilerOptions": {
    "target": "es2015",
    "module": "esnext",
    "jsx": "react-jsx",
    "noImplicitAny": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "esModuleInterop": true,
    "lib": ["dom", "esnext"],
  },
  "include": ["src"]
}

最后,创建 vite.config.js 文件并添加以下内容:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }
})

创建组件

src 目录下创建一个名为 App.vue 的文件并添加以下内容:

<template>
  <div>Hello Vite + Vue 3 + TypeScript!</div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'App',
  components: {},
  setup() {
    return {}
  }
})
</script>

运行项目

在项目根目录运行以下命令启动项目:

npm run dev

配置多语言版本

要配置多语言版本,需要执行以下步骤:

  1. 安装 vue-i18n 依赖项:
npm install vue-i18n --save
  1. src 目录下创建 i18n 目录。

  2. i18n 目录下创建 en.jsonzh-CN.json 文件,分别添加以下内容:

// en.json
{
  "hello": "Hello",
  "world": "World"
}

// zh-CN.json
{
  "hello": "你好",
  "world": "世界"
}
  1. main.ts 文件中添加以下代码:
import { createI18n } from 'vue-i18n'

const messages = {
  en: require('./i18n/en.json'),
  'zh-CN': require('./i18n/zh-CN.json')
}

const i18n = createI18n({
  locale: 'en',
  messages
})

export default i18n
  1. App.vue 文件中添加以下代码:
<template>
  <div>{{ $t('hello') }} {{ $t('world') }}!</div>
</template>

再次运行项目,即可看到多语言版本的内容。

常见问题解答

  1. 如何更改项目语言?
    更改语言的方法是修改 main.ts 文件中 locale 的值。

  2. 如何添加新语言?
    要添加新语言,需要创建新的 JSON 文件并将其放置在 i18n 目录下。

  3. 如何在组件中使用多语言文本?
    可以使用 $t() 方法在组件中使用多语言文本。

  4. 如何设置默认语言?
    可以在 i18n 实例中设置默认语言,如下所示:

const i18n = createI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages
})
  1. 如何切换语言时更新组件?
    当切换语言时,可以使用 watch 观察者来更新组件,如下所示:
export default defineComponent({
  name: 'App',
  components: {},
  setup() {
    const { locale } = useI18n()
    watch(locale, () => {
      // 更新组件
    })
    return {}
  }
})