在VS2012中的TypeScript项目中使用JavaScript项目

时间:2014-01-27 06:17:03

标签: javascript visual-studio-2012 typescript

我安装了Node.js工具(https://nodejstools.codeplex.com/),我有一个项目,我可以在一个正常工作的本地文件上运行。对于Web应用程序,我想使用TypeScript(我稍后可能会以某种方式将我的node.js代码迁移到TS)。只需在我的其他项目中调用一个函数。

这是我用来调用我的函数的可执行文件(compiler.compile)

var compiler = require("../src/compiler"),
    fs       = require("fs");


fs.readFile(process.argv[2], 'utf8', function(err, data) {
    if (err) {
        console.log("FILE READ ERROR: ", err);
        process.exit();
    }

    var output = compiler.compile(data);
});

这就是我导出它的方式:

exports.compile = function(code) {
    //code
};

如何在VS2012 TS项目中使用我的compile()函数?

我试过了:

<script src ="compiler.js"></script>
<script src="app.js"></script>

declare function compile(code:String);

但这似乎不起作用。

编辑:我也试过这样做:

compiler.js

exports.compile = function() {};

compiler.d.ts

declare module "compiler.js" {
        class Compiler {
            compile();
        }
    }

app.ts

///<reference path="./compiler.d.ts"/>
import compiler = module("compiler.js");

但是我在app.ts的“import compiler = module”下得到了一个错误的行,说“模块不能别名为非模块类型。无法解析模块引用'模块'。”

所有3个文件都在同一文件夹和项目中进行测试。

EDIT2 :我设法让它识别compile.d.ts中的模块,即使用'require'而不是'module'移动到我的JS项目,但它没有似乎链接到我的compiler.js文件中的函数。事实上,我没有看到任何地方将JS函数链接到d.ts声明的任何内容,这很令人困惑。

1 个答案:

答案 0 :(得分:0)

我可能不完全理解你的问题,但我相信你需要......

compiler.d.ts

declare var compile: (code: string) => any;

export = compile;

app.ts

import compile = require('./compiler');

compile('Code In Here');

您应该在import语句中省略文件扩展名。最新版本的TypeScript使用require而非module(如您所发现的)。如果仅使用compile(str)调用该函数,则声明不需要以任何方式包装函数。如果你确实希望它包装在一个模块和类中,请记住模块是文件,因此你需要模块声明(如下面的备用compiler.d.ts所示)。

declare class CompilerClass {

    compile(code: string): any;

}

这将使用如下:

import Compiler = require('/compiler');

var compiler = Compiler.CompilerClass();

compiler.compile('Code here');