假设a具有以下TypeScript模块:
function foo () {
return 123;
}
//TODO: Export code here
我想以一种可以从TypeScript中导入的方式导出它:
import foo from 'foo';
import * as foo from 'foo';
并以这种方式从Node:
const foo = require ( 'foo' );
要求:
allowSyntheticDefaultImports
选项到目前为止,我已经提出了以下“解决方案”,但是它们要么不能很好地保留类型定义,要么太冗长:
export = foo['default'] = foo as typeof foo & { default: typeof foo };
export = foo['default'] = foo;
有更好的方法吗?
答案 0 :(得分:0)
据我所知,NodeJS还不支持导出和导入。 查看本文:node-js-syntaxerror-unexpected-token-import
据我所知,使用TypeScript类型语法的唯一方法是仅在.ts
文件中,因此一种选择是使用Babel将所需的.ts
文件编译为.js
。
答案 1 :(得分:0)
由于您是作为commonjs软件包发布的,因此不需要汇总/ webpack。
您需要做的就是使用TypeScript编译器将代码转换为commonjs中的es5。
您的tsconfig.json应该如下所示:
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"target": "es5",
"outDir": "dist" // customize this yourself.
...
}
}
在您的package.json中:
// package.json
{
"main": "dist/index.js",
"typings": "dist/inde.d.ts",
"files": [
"dist" // customize this yourself.
],
...
}
这是一个示例存储库,您可以查看以下内容:
答案 2 :(得分:0)
这是我能想到的最好的方法:
chrome.exe --allow-file-access-from-files
非常简洁,可以正确生成类型定义,并且可以使用上述所有方法将其导入。