Первые пользователи Vue3 и TSX
Основные задействованные зависимости
-
vite@1.0.0-beta.11: Леса нового поколения -
vue@3.0.0-beta.22: бета-версия vuex@4.0.0-beta.4vue-router@4.0.0-beta.2typescript@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>
Интегрированный ТС
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",
},
};
Встроенный принтер
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-маршрутизатор
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;
Способ создания маршрутизатора здесь отличается от предыдущего, в 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
Наконец, store и router представлены в main.ts:
import { createApp } from 'vue';
import App from './App';
import router from './router';
import store from './store';
createApp(App).use(router).use(store).mount('#app');
конец
Выпуск официальной версии vue3 неизбежно приведет к коллективному обновлению окружающих фреймворков vue2, таких как фреймворк пользовательского интерфейса, библиотека инструкций на основе Vue2 и т.д. к построению сообщества vue3.
Комбинация Vue3 и TS — основная тенденция, если вам не подходит TS, рекомендуется использовать Vue2. 23333~
Последующие блоггеры также изучат новые функции и API-интерфейсы платформы vite и корзины семейства vue3 и будут стремиться создавать высококачественные документы.
Наконец, адрес исходного кода прилагается:GitHub.com/предположительно Twiner/V…
Справочная статья:GitHub.com/hyper Мосс/В…