获取错误:如何从打字稿中正确使用我的转录和打字的打字稿npm模块?
我仍然打字打字。 我写了一个简单的“hello world”打字稿模块,并将其发布到npm 。 真的很平凡,只是做一个默认导出:
export default function hello(target: string = 'World'): void { console.log(`Hello, ${target} :-(`) }
它被node.js 0.10 – > 6消耗得非常好。该模块在package.json中也具有适当的"typings"
属性,指向由tsc生成的现有的.d.ts
文件, 正如在官方文档中所解释的 :
export default function hello(target?: string): void;
但是,打字稿1.8和2都不能打印它,
import hello = require('hello-world-emo') hello() hello('Offirmo')
使用tsc
传输或使用ts-node
执行都会给出相同的错误消息:
TSError: ⨯ Unable to compile TypeScript hello.ts (3,1): Cannot invoke an expression whose type lacks a call signature. (2349)
但是,生成的.js起作用。 这只是一个打字问题。 使用其他导入格式,如import hello from 'hello-world-emo'
中的import hello from 'hello-world-emo'
也不起作用。
什么是打字稿抱怨? 我错过了什么 ?
如果你想检查tsconfig
,模块在这里 ,我从这里消耗它
问题不在打字稿中,而是在ES6 / CommonJS interop中 :ES6和CommonJS输出之间没有完美的匹配, 尤其是对于ES6的“输出默认” 。 本文和webpack上的这个公开问题 。
这里模块代码是使用ES6模块在ES6中编写的。 构build过程是:
- 使用
tsc
(打字稿编译器)将打字稿打印到ES6 - 编译ES6代码并将其与
rollup
+ babel绑定:- ES6 @ node4 / CommonJS(一等公民)
- ES5@node0.10 / CommonJS(仍然广泛使用的遗产)
- ES5 / umd(浏览器)
节点4(stable)是第一类公民,相应的包(ES6 @ node4 / CommonJS)通过npm“main”条目公开。 它已经被转换为CommonJS,就像汇总可以做的那样,使得它可以被节点4消耗,但不再被打字机消耗 。
另一个select是用tsc
将其转换为ES5 / CommonJs, 这会为CommonJS链接到ES6模块添加特殊的注释 。 但是,这是1)不再捆绑2)更粗略地转换(不使用包含在节点4中的ES6function)3)节点更难以消耗
一个折中的解决scheme :通过不使用export default
而只使用命名导出来避免CommonJS / ES6模块互操作问题。 这种缓解技术的唯一缺点是节点4:
- ES6:
import hello from '...'
import { hello } from '...'
OK - node> = 6:
const hello = require('...')
变为const { hello } = require('...')
OK - node <= 4:
var hello = require('...')
变成var hello = require('...').hello