Vue3與TSX嚐鮮版
涉及到的主要依賴
-
vite@1.0.0-beta.11
:新一代腳手架 -
vue@3.0.0-beta.22
:beta版 vuex@4.0.0-beta.4
vue-router@4.0.0-beta.2
typescript@3.9.6
準備工作
- 確保安裝
yarn
npm install yarn -g
- 確保安裝
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.json
:
{
"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.js
:
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.js
:
module.exports = {
semi: true,
trailingComma: "all",
singleQuote: true,
printWidth: 100,
tabWidth: 2,
endOfLine:"auto"
};
到這一步,一個Vue3+TSX的專案就搭建起來了,以上配置檔案的具體內容就不做解釋了。
修改入口檔案
因為預設專案模板是以src/main.js
為入口的,我們需要把它修改為src/main.ts
。
在根目錄的index.html
中修改入口檔案的引用即可:
... ...
<body>
... ...
<script type="module" src="/src/main.ts"></script>
</body>
</html>
優化TS型別推斷
在src目錄下,建立shim.d.ts、source.d.ts
shim.d.ts
: (這個其實不太需要,因為專案中全是通過tsx開發的)
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}
source.d.ts
: (優化編譯器提示,宣告靜態資原始檔)
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
:
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的型別推斷,開發效率會高很多。
整合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