简体   繁体   中英

Using a JavaScript project in a TypeScript project in VS2012

I installed Node.js Tools ( https://nodejstools.codeplex.com/ ) and I have a project I can run on a local file that works properly. For the web application, I want to use TypeScript (I will later perhaps migrate my node.js code to TS somehow). Simply to call a function in my other project.

This is the executable I use to call my function (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);
});

And this is how I export it:

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

How would I go about using my compile() function in a VS2012 TS project?

I tried:

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

and:

declare function compile(code:String);

But that doesn't seem to work.

EDIT : I have also tried doing this:

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");

But I'm getting a squigly line under "import compiler = module" in app.ts saying "Module cannot be aliased to a non-module type. Unable to resolve module reference 'module'."

All 3 files are in the same folder and project for testing.

EDIT2 : I managed to get it to recognize the module in compiler.d.ts, even when moved to my JS project by using 'require' instead of 'module' but it doesn't seem to link to my function in my compiler.js file. In fact, I don't see anything linking the JS functions to the d.ts declarations anywhere, and it's pretty confusing.

I may not fully understand your question, but I believe you need...

In compiler.d.ts

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

export = compile;

In app.ts

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

compile('Code In Here');

You should leave out the file-extension in the import statement. The latest version of TypeScript uses require rather than module (as you discovered). If the function is just called using compile(str) the declaration doesn't need to wrap the function in any way. If you do want it wrapped in a module and class, just bear in mind that the module is the file, so you need to module declaraion (as shown below in the alternate compiler.d.ts).

declare class CompilerClass {

    compile(code: string): any;

}

This would be used as follows:

import Compiler = require('/compiler');

var compiler = Compiler.CompilerClass();

compiler.compile('Code here');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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