新建一个 Vue 3.0 + Vite + ts 项目

1,974 阅读3分钟

1. 新建项目

# 新建一个名字 blog 的项目
yarn create @vitejs/app blog
## 选择 Vue -> Vue ts
# 安装依赖
yarn
# 运行项目
yarn dev

可以看到已经成功启动服务: http://localhost:3000

2. 关联 git 仓库

  1. 新建 git 仓库
  2. 关联本地与远程仓库
# 初始化 git 环境
git init
# 关联仓库地址
git remote add origin <仓库地址>
# 添加文件
git add .
# 提交信息
git commit -m'ci(index): first commit'
# 上传分支
git push --set-upstream origin master

3. 设置本机IP地址为默认服务IP

这种设置可以为与后端联调 提供方便, 无需每次获取 本机 IP 地址更改, 特别适合多人在局域网合作开发

  1. 下载 node 的 os 模块: yarn add os

os 模块提供了与操作系统相关的实用方法和属性, 我们可以通过这个模块获取一些电脑本机信息

  1. 在项目根路径的 vite.config.ts文件中修改
// 引入 os 模块
import os from 'os'

// 获取本机IP地址
const NETWORK = os.networkInterfaces().WLAN
const IP = NETWORK.filter((ip: { family: 'IPv4' | 'IPv6', address: string }) => ip.family === 'IPv4')[0].address

// 设置默认服务IP 与 端口
export default defineConfig({
  // 与 服务相关使用 server 配置
  server: {
    host: IP || '127.0.0.1' || 'localhost',
    port: 9527
  }
})
  1. 重启服务就可以看到 本来是 localhost的地方,变成了我们本机的 ip 地址

image.png

4. 配置多语言: vue-i18n@next

  1. 下载多语言依赖: yarn add vue-i18n@next
  2. 在src的路径下新建 locale文件夹

image.png

  1. 新增多语言分类

    en-US.ts

    export default  {
      name: 'blog'
    }
    

    zh-CN.ts

    export default  {
      name: '博客'
    }
    
  2. 配置 index.ts

    注意点: vite 提供了 glob引入, 可以使用特殊的 import.meta.glob 函数从文件系统导入多个模块. 文献: cn.vitejs.dev/guide/featu…
    如: const modules = import.meta.glob('./文件夹/*.ts'), 可以遍历 modules 对象的 key 值来访问相应的模块, 这样的文件是懒加载的.
    如果想直接导入所有的模块,而不是懒加载, 可以使用import.meta.globEager , 如: const modules = import.meta.globEager('./文件夹/*.js')

    // 引入多语言
    import { createI18n, LocaleMessages, VueMessageType } from 'vue-i18n'
    
    // 参考 https://cn.vitejs.dev/guide/features.html#glob-import 导入同文件夹下多个ts模块
    const modules = import.meta.globEager('./*.ts')
    // 获取全部语言文件
    const getAllLang: () => LocaleMessages<VueMessageType> = () =>{
      const message: LocaleMessages<VueMessageType> = {}
      // 获取所有存有语言的文件
      for(let path in modules) {
        // 规定所有的多语言均为 4位
        const key: string = path.slice(path.lastIndexOf('/') + 1, path.lastIndexOf('.'))
        const value = modules[path].default
        message[key] = value
      }
      return message
    }
    
    // 获取当前语言
    type ILocale = 'en-US' | 'zh-CN'
    const locale: ILocale = 'zh-CN'
    
    const i18n = createI18n({
      locale,
      messages: getAllLang()
    })
    
    export default i18n;
    
  3. main.ts中注册多语言

    import { createApp } from 'vue'
    import App from './App.vue'
    import VueI18n from './locale'
    
    let app = createApp(App);
    app.use(VueI18n)
    app.mount('#app')
    
  4. 在页面使用App.vue

    <template>
      <div>{{ t('name') }}</div>
    </template>
    
    <script lang="ts">
    import { useI18n } from "vue-i18n";
    import { defineComponent } from 'vue'
    
    export default defineComponent({
      name: 'App',
      setup() {
        const { t } = useI18n();
        return{ t }
      }
    })
    </script>
    

5. 配置 scss

  1. 下载sass: yarn add -D sass

  2. 这样就可以在页面使用了:

    <style lang="scss">
    $bg-color: #f00;
    .tt {
      background: $bg-color;
    }
    </style>
    
  3. 如果需要提供公共的scss文件, 可以配置一下 vite.config.ts

    vite.config.ts

    // path报错 需要安装 Node 声明: yarn add @types/node -D
    const path = require('path')
    export default defineConfig({
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: `@import "./src/style/index.scss";`
          }
        }
      }
    })
    
  4. 在根目录创建 style文件夹

image.png index.ts

$text-color: #00f;
  1. 使用:

    App.vue

    <template>
      <div class="tt">{{ t('name') }}</div>
    </template>
    
    <style lang="scss">
    $bg-color: #f00;
    .tt {
      color: $text-color;
      background: $bg-color;
    }
    </style>
    

    6. 配置 axios

    安装依赖命令: vue add axios

image.png

然后就会发现在目录下, 多了一个 plugins

image.png

自动生成的axios.js如下

"use strict";

import Vue from 'vue';
import axios from "axios";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;