我刚刚将我的第一个库包发布到 NPM,我正在尝试在应用程序项目中使用它。
它是用打字稿编写的,项目构建正常,并已发布到 NPM。但是尝试使用它失败了,因为显然它不是一个有效的模块。
index.ts 文件中用于设置模块导出 (afaik( 的代码为:
const initByClass = (widgetBindings: WidgetClassBinding[], h: any, render: any) => {
for (const widgetBinding of widgetBindings) {
setupWidget(widgetBinding, h, render);
}
};
module.exports = {
initByClass
};
库中的 tsconfig.json 文件是:
{
"compilerOptions": {
"esModuleInterop": true,
"target": "ES6",
"module": "ES6",
"moduleResolution": "node",
"declaration": true,
"outDir": "./lib",
"strict": true
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]
}
在我的应用程序代码中,我已将包添加到我的package.json(并运行npm update(,并尝试将其导入应用程序入口文件中:
import { initByClass } from "widgety";
但它给了我一个错误:
TS2306:文件"/var/app/app/node_modules/widgety/src/index.ts"不是 模块。
我需要更改什么才能使代码可导入到另一个打字稿项目中?
如果它们有用,则所有项目文件:https://github.com/Danack/widgety/和 NPM 包条目:https://www.npmjs.com/package/widgety
当文件使用export
关键字导出值时,它被视为模块。
我相信用这一行替换module.exports =
,应该可以修复错误:
export default initByClass;
请参阅此文档:https://www.typescriptlang.org/docs/handbook/modules.html
在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级
import
或export
的文件都被视为模块。相反,没有任何顶级导入或导出声明的文件被视为其内容在全局范围内可用的脚本(因此也可用于模块(。
使用import
或export
使编译器将文件视为模块,而分配给module.exports
或使用require()
则不会。
出于这个原因和其他原因,总是在打字稿代码库中使用import
和export
。