Rollup + TypeScript 编译类型声明文件
无法找到模块“@superying/remote-ui”的声明文件...
@types/ 没有维护响应的类型库,则需要自己手动在
.d.ts 文件中声明:
// 如 global.d.tsdeclare module '@superying/remote-ui'
1.使用 tsc 编译类型文件
"compilerOptions": {"declaration": true, /* 生成相关的 '.d.ts' 文件。*/"declarationDir": "./dist/types", /* '.d.ts' 文件输出目录 */"emitDeclarationOnly": true, /* 只生成声明文件,不生成 js 文件*/"rootDir": "./src", /* 指定输出文件目录(用于输出),用于控制输出目录结构 */}
tsconfig.types.json 文件中,专门用来做类型声明编译用。(
注:由于 rollup 通过 rollup-plugin-typescript2 插件识别 TypeScript 语法,默认配置文件 tsconfig.json 给此插件使用,且仅包括常用配置)。
tsc -b ./tsconfig.types.json
2.如何让类型声明文件被引用
package.json 中配置
types 属性,将其指向生成的类型声明文件。下面是我的
package.json 的相关配置,包括
types 配置及编译类型声明文件的
npm script:
{"name": "@superying/remote-ui","version": "1.0.6","main": "./dist/index.js","module": "./dist/index.esm.js","types": "./dist/types/index.d.ts", // 指向 tsc 读取的类型声明文件"umd": "./dist/index.umd.js","devDependencies": { /** 省略.... */ },"scripts": {"clean:dist": "rimraf dist","build:types": "npm run clean:dist && tsc -b ./tsconfig.types.json", // 编译类型"build": "npm run build:types && rollup -c","build:min": "npm run build:types && cross-env NODE_ENV=production rollup -c","test": "node test/test.js","pretest": "npm run build"},"files": [ "dist" ]}
“
无法找到模块 xxx 的声明文件
” 的报错折磨啦。
