转向使用TypeScript
首先
个人开发备忘录?
我正在使用TypeScript重写正在开发中的日历应用程序。
※我在laravel中使用Vite引入了React。
在Vite中,TypeScript是如何进行构建的。
简单看了下,我进行了一下调查。
Vite起動
↓
vite.config.jsの設定に基づき、プロジェクトがビルドされる
↓
エントリーポイントとなる ex) resources/js/app.tsxファイルからビルドが開始される
エントリーポイントファイルには、Viteの読み込みや初期化が含まれる
↓
Viteで、依存関係の解決や読み込み・解析を行う
↓
開発者は、ViteのHMR(ホットモジュールリプレースメント)機能を使用し、ブラウザで即座に反応が見れる
↓
Viteはビルド後、ブラウザから読み取れるようにするため、javascriptファイルに変換されたファイルを生成する
进行设置以便使用TypeScript。
安装TypeScript
cd プロジェクトディレクトリ
npm install --save-dev typescript @types/react @types/react-dom
创建 tsconfig.json 文件
在 tsconfig.json 文件中,我们需要写下要编译的文件以及要使用的选项。
参考网站 → https://typescript-jp.gitbook.io/deep-dive/project/compilation-context
{
"compilerOptions": {
"target": "ESNext",
"lib": ["dom", "dom.iterable", "esnext"],
"jsx": "react",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
},
"include": ["resources/js/**/*"],
"exclude": ["node_modules"]
}
“include”指定了TypeScript编译的文件。
“exclude”指定了不需要编译的文件。
在本例中,我们将resources/js目录下的所有文件都作为编译目标。
“exclude”指定了不需要编译的文件。
在本例中,我们将resources/js目录下的所有文件都作为编译目标。
编辑vite.config.js文件
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.tsx', //.tsxに変更
refresh: true,
}),
react(),
],
});
在这里,您可以指定在Vite启动后要构建的文件。
编辑app.tsx(本次的入口文件)。
import React from 'react';
import { createInertiaApp } from '@inertiajs/react'
import { createRoot } from 'react-dom/client';
createInertiaApp({
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.tsx', { eager: true })
return pages[`./Pages/${name}.tsx`] || pages[`./Pages/admin/${name}.tsx`]
},
setup({ el, App, props }) {
createRoot(el).render(<App {...props} />)
},
});
参考网站→https://search.readouble.com/?query=10.x+createInertiaApp
此处的详细内容将稍后更新。
编辑基础的blade文件
因为下面的blade文件正在加载react文件,所以我也会在这里进行修正,改为.tsx文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Styles -->
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<!-- Script -->
@viteReactRefresh
@vite('resources/js/app.tsx') // .tsxに変更
@inertiaHead
</head>
<body>
@inertia
</body>
</html>
将resources/js目录下的文件扩展名改为.tsx。
因为只是更改了文件的扩展名,所以这部分省略。
我已经进行了上述更改,并且已暂时在本地显示,但由于每个React文件出现错误,因此将其更新到另一篇文章中。