我已经构建了一个npm包,它是Typescript,由于某种原因,它不能生成类型定义文件,而当我尝试运行它时,我会得到经典的Could not find a declaration file for module...
我尝试将types
和typings
添加到package.json中没有任何运气。
package.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
不会导致生成文件。就其价值而言,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/**/*"]
}
答案 0 :(得分:0)
将declaration
添加到compilerOptions
文件的tsconfig.json
部分。
"declaration": true, /* Generates corresponding .d.ts file. */
或者,将您的build
脚本更改为包含--declaration
。
"build": "tsc --declaration"
这两个选项都将导致npm run build
生成声明文件。
然后通过添加指向主声明文件的package.json
属性来更新types
文件。在以下示例中,我假设您的主声明文件位于./index.d.ts
中。
"main": "index.js",
"types": "index.d.ts",
the Publishing docs的开头部分详细介绍了答案。
还有其他compiler options here。以下三种情况可能对您有用:
declarationDir
生成的声明文件的输出目录。declarationMap
为每个相应的.d.ts
文件生成一个源映射。emitDeclarationOnly
仅发出.d.ts
声明文件。当您已经使用babel
将文件从TypeScript转换为JavaScript并且只想使用TypeScript生成声明文件并执行类型检查时,列表中的最后一个选项很方便。