Vue3全家桶 + Vite + TS + TSX嚐鮮,先人一步!

Vue3與TSX嚐鮮版

涉及到的主要依賴

  1. vite@1.0.0-beta.11:新一代腳手架
  2. vue@3.0.0-beta.22:beta版
  3. vuex@4.0.0-beta.4
  4. vue-router@4.0.0-beta.2
  5. typescript@3.9.6

準備工做

  1. 確保安裝yarn
npm install yarn -g
  1. 確保安裝vite腳手架
npm install -g create-vite-app
# or
yarn add -g create-vite-app

開始

項目初始化

yarn create vite-app <project-name>

集成TS

yarn add --dev typescript

項目根目錄建立配置文件:tsconfig.jsoncss

{
  "include": ["./**/*.ts"],
  "compilerOptions": {
    "jsx": "react",
    "target": "es2020" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    // "lib": ["es2017.object"] /* Specify library files to be included in the compilation. */,
    // "declaration": true /* Generates corresponding '.d.ts' file. */,
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true /* Generates corresponding '.map' file. */,
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./dist" /* Redirect output structure to the directory. */,

    "strict": true /* Enable all strict type-checking options. */,
    "noUnusedLocals": true /* Report errors on unused locals. */,
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,

    "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
  }
}

集成eslint

yarn add --dev eslint eslint-plugin-vue

項目根目錄建立配置文件.eslintrc.jshtml

module.exports = {
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser', // Specifies the ESLint parser
    ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
    sourceType: 'module', // Allows for the use of imports
    ecmaFeatures: {
      // tsx: true, // Allows for the parsing of JSX
      jsx: true,
    },
  },
  // settings: {
  //   tsx: {
  //     version: "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
  //   }
  // },
  extends: [
    'plugin:vue/vue3-recommended',
    'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
    'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
    'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
  ],
  rules: {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  },
};

集成pritter

yarn add --dev prettier eslint-config-prettier eslint-plugin-prettier

項目根目錄建立配置文件:.prettierrc.jsvue

module.exports = {
  semi: true,
  trailingComma: "all",
  singleQuote: true,
  printWidth: 100,
  tabWidth: 2,
  endOfLine:"auto"
};

到這一步,一個Vue3+TSX的項目就搭建起來了,以上配置文件的具體內容就不作解釋了。node

修改入口文件

由於默認項目模板是以src/main.js爲入口的,咱們須要把它修改成src/main.ts
根目錄的index.html中修改入口文件的引用便可:react

... ...
<body>
  ... ...
  <script type="module" src="/src/main.ts"></script>
</body>
</html>

優化TS類型推斷

在src目錄下,建立shim.d.ts、source.d.ts git

shim.d.ts: (這個其實不太須要,由於項目中全是經過tsx開發的)github

declare module '*.vue' {
  import Vue from 'vue';
  export default Vue;
}

source.d.ts: (優化編譯器提示,聲明靜態資源文件)vue-router

declare const React: string;
declare module '*.json';
declare module '*.png';
declare module '*.jpg';

集成vue-router

yarn add --dev vue-router@4.0.0-beta.2

這裏能夠去npm官網查找最新版本
在src目錄下,新建router文件夾,並在文件夾內建立index.ts
index.ts:vuex

import { RouteRecordRaw, createRouter, createWebHistory } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: import('../views/Home'),
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About'),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

這裏建立router的方式與以前不一樣,在vue3中,結合TS的類型推斷,開發效率會高不少。typescript

集成vuex

yarn add --dev vuex@4.0.0-beta.4

在src目錄下,新建store文件夾,並在文件夾內建立index.ts

index.ts:

import { state } from './state';
import { createStore } from 'vuex';

export default createStore({
  state,
  mutations: {},
  actions: {},
  modules: {},
});

state.js:

export interface State {
  title: string;
}

export const state: State = {
  title: 'Vue(v3) 與 tsx 的結合~',
};

main.ts

最終main.ts中引入store、router:

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

createApp(App).use(router).use(store).mount('#app');

TSX

最終咱們的組件代碼,都會是這樣的:App.tsx:

import { defineComponent } from 'vue';
import {RouterLink, RouterView} from 'vue-router';
import './style/main.scss'

export default defineComponent({
  name: 'App',
  setup() {
    return () => (
      <>
        <div id="nav">
          <RouterLink to="/">Home</RouterLink> |
          <RouterLink to="/about">About</RouterLink>
        </div>
        <RouterView/>
      </>
    );
  }
});

自我感受TSX比模板好多了,而且html、組件標籤的屬性都帶有類型推斷。

結尾

vue3正式版的發佈,勢必致使vue2的周邊框架的集體更新,例如UI框架、基於Vue2的指令庫等,做爲這麼久的白嫖黨,也要爲vue3社區的建設出一份力了。

Vue3與TS的結合是大趨勢,若是不適應TS,那仍是建議使用Vue2吧。23333~

後續博主也將研究vite框架和vue3全家桶的新特性與API,爭取輸出有質量的文檔。


最後附上源碼地址: https://github.com/justwiner/vue3-tsx


參考文章: https://github.com/hyperMoss/vue-tsx

相關文章
相關標籤/搜索