简体   繁体   English

Typescript可以导入CommonJS模块吗?

[英]Can Typescript import CommonJS Modules?

I had this file: 我有这个文件:

//foo.js
var foo = function () {
    return "foo";
}; 

module.exports = foo;

So, I wanted to import it to my Typescript file. 所以,我想将它导入我的Typescript文件。 I tried this 我试过这个

//typescript.ts
import * as foo from ("./foo");

Didn't work. 没工作。 I read about this 'ambient' modules, so I added this 我读到了这个'环境'模块,所以我添加了这个

//typescript.ts
/// <reference path="./foo.d.ts" />
import * as foo from ("./foo");

And I added a "foo.d.ts" file in the same folder, which had the purpose of letting typescript know about the types of my imported function: 我在同一个文件夹中添加了一个“foo.d.ts”文件,其目的是让打字稿知道导入函数的类型:

declare module "foo" 
{
    function foo(): string
    export = foo;
}

No luck. 没运气。

I thought that the problem was with the import syntax (you cannot have the same syntax for es6 and commonjs modules, right?). 我认为问题出在导入语法上(对于es6和commonjs模块,你不能使用相同的语法,对吧?)。 So I did this. 所以我这样做了。

import foo = require("./foo");

As you might guess, that didn't work either. 正如您可能猜到的那样,这也不起作用。

I have been able to import d3 an use it successfully when I installed it as a node module with npm install d3 and referenced its d.ts file. 当我使用npm install d3将其npm install d3为节点模块并引用其d.ts文件时,我能够成功导入d3并成功使用它。 I did it with this code: 我用这段代码做了:

import * as d3 from "d3";

I haven't been able to do the same with any other module (jquery, box2d, box2d-commonjs, among others), nor with my own libraries as demonstrated above. 我无法对任何其他模块(jquery,box2d,box2d-commonjs等)以及我自己的库(如上所示)执行相同的操作。 I am new to Typescript, so probably I'm missing something very obvious, but I haven't been able to figure it out by myself. 我是Typescript的新手,所以可能我错过了一些非常明显的东西,但我自己也无法弄明白。

Turns out it was something really obvious: you had to use the --allowJs option. 事实证明这是非常明显的:你必须使用--allowJs选项。 This worked for me: 这对我有用:

tsc --moduleResolution "node" --module "commonjs"  --allowJs main.ts

Though, I still can't figure out why d3 worked while the others libraries didn't. 虽然,我仍然无法弄清楚为什么d3工作,而其他图书馆没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM