gpt4 book ai didi

reactjs - 自定义 Typescript NPM 包不会生成类型

转载 作者:行者123 更新时间:2023-12-04 17:36:17 24 4
gpt4 key购买 nike

我有一个我构建的 npm 包,它是 Typescript,由于某种原因,在构建时,它没有生成类型定义文件,当我尝试运行它时,我得到了经典的 Could not find a declaration file对于模块...

我试过将 typestypings 添加到 package.json 但没有成功。

包.json

{
"name": "@org/mypackage",
"version": "0.0.7",
"description": "",
"main": "index.js",
"transform": {
"^.+\\.(ts|tsx)?$": "<rootDir>/node_modules/babel-jest"
},
"scripts": {
"build": "tsc"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sample/sample.git"
},
"author": "Ken M",
"license": "ISC",
"bugs": {
"url": "https://github.com/sample/sample/issues"
},
"homepage": "https://github.com/sample/sample#readme",
"dependencies": {
"@types/jest": "^24.0.13",
"@types/node": "12.0.2",
"@types/react": "16.8.17",
"@types/react-dom": "16.8.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"tachyons": "^4.11.1"
},
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/preset-react": "^7.0.0",
"@typescript-eslint/eslint-plugin": "^1.9.0",
"@typescript-eslint/parser": "^1.9.0",
"awesome-typescript-loader": "^5.2.1",
"babel-jest": "^24.8.0",
"babel-preset-react": "^6.24.1",
"eslint": "^5.16.0",
"eslint-config-prettier": "^4.3.0",
"eslint-plugin-prettier": "^3.1.0",
"prettier": "^1.17.1",
"typescript": "^3.4.5"
}
}

tsconfig.json

请参阅下面的 tsconfig.json。向其中添加 declaration: true 不会导致生成文件。对于它的值(value),main: index.js 也没有生成。

{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"outDir": "./dist",
"jsx": "react",
"declaration": true
},
"include": ["src/**/*"]
}

最佳答案

简答

declaration 添加到 tsconfig.json 文件的 compilerOptions 部分。

"declaration": true, /* Generates corresponding .d.ts file. */

或者,更改您的build 脚本以包含--declaration

"build": "tsc --declaration"

这两个选项都会导致 npm run build 生成声明文件。

然后通过添加指向主声明文件的 types 属性来更新您的 package.json 文件。在下面的示例中,我假设您的主要声明文件位于 ./index.d.ts

"main": "index.js",
"types": "index.d.ts",

其他详细信息

开篇the Publishing docs有关于答案的更多细节。

还有额外的compiler options here .以下三个可能对您的情况有用:

  • declarationDir 生成的声明文件的输出目录。
  • declarationMap 为每个相应的 .d.ts 文件生成一个 sourcemap。
  • emitDeclarationOnly 只发出 .d.ts 声明文件。

当您已经使用 babel 将文件从 TypeScript 转换为 JavaScript 并且只想使用 TypeScript 生成声明文件并执行类型检查时,列表中的最后一个选项很方便。

关于reactjs - 自定义 Typescript NPM 包不会生成类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56568958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com