我正在努力让 Vite 为我的 React TypeScript 库生成
.d.ts
声明文件。运行 npm run build 后,dist 文件夹中仅存在 main.js 和 main.css 文件。
我确实看到,在构建过程中,在
.d.ts
文件夹中创建了包括 dist/
文件在内的多个文件,但是当构建完成后,所有内容都会再次删除,只有 main.js
文件和 main.css
文件保留在那里。
我尝试更改或省略
noEmit
、declaration
、declarationMap
和 emitDeclarationOnly
中的值,但没有成功。我在互联网上找到的示例似乎都不起作用。我的项目结构
tsconfig.app.json
Vite 应该创建一个
package.json
tsconfig.json
tsconfig.app.json
tsconfig.node.json
vite.config.js
/src/main.ts
/src/SomeComponent.tsx
/src/SomeHook.ts
文件夹,其中包含
dist/
文件和 main.js
文件,其中包含 React main.d.ts
和 SomeComponent
的所有类型信息。我的SomeHook
main.ts
export { SomeComponent } from './SomeComponent';
export { useSomeHook } from './useSomeHook';
的示例:
useSomeHook.ts
我的Vite配置
type UseSomeHookProps = {
someArg?: () => void;
};
export const useSomeHook = ({ someArg }: UseSomeHookProps = {}) => {
return { ... };
};
我的
/// <reference types="vite/client" />
import { defineConfig } from 'vite'
import { libInjectCss } from 'vite-plugin-lib-inject-css'
import react from '@vitejs/plugin-react'
import dts from 'vite-plugin-dts'
export default defineConfig({
plugins: [
react(),
libInjectCss(),
dts({
entryRoot: 'src',
outDir: 'dist',
}),
],
build: {
lib: {
entry: './src/main.ts',
name: 'ReactWizard',
fileName: 'main',
formats: ['es'],
},
rollupOptions: {
external: ['react', 'react-dom', 'react/jsx-runtime'],
output: {
globals: {
react: 'React',
'react-dom': 'React-dom',
'react/jsx-runtime': 'react/jsx-runtime',
},
},
},
},
})
tsconfig.app.json
我的package.json
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": false,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true,
"outDir": "dist",
},
"include": ["src"],
}
终端输出
{
"name": "some-package",
"version": "0.0.0",
"type": "module",
"files": [
"dist"
],
"exports": "./dist/main.js",
"module": "./dist/main.js",
"types": "./dist/main.d.ts",
"scripts": {
"build": "tsc -b && vite build",
...
},
"dependencies": {
...
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
"typescript": "~5.6.2",
"vite": "^6.0.5",
"vite-plugin-dts": "^4.4.0",
...
}
}
终端输出为:
npm run build
如果使用官方Vite模板启动,需要指定tsconfigPath:
> tsc -b && vite build
vite v6.0.6 building for production...
✓ 189 modules transformed.
[vite:dts] Start generate declaration files...
computing gzip size (0)...[vite:dts] Declaration files built in 1074ms.
dist/main.css 6.63 kB │ gzip: 1.74 kB
dist/main.js 23.50 kB │ gzip: 7.85 kB
✓ built in 1.97s
参考:https://github.com/qmhc/vite-plugin-dts