简体   繁体   中英

NodeJS: Import all local variables

I have a project on TypeScript and I need to run compiled JS file on NodeJS. The problem is I can't change TypeScript file. The problem is TypeScript compiler makes var mymodule and attaches all variables and functions to this var . And I don't know how to import this module to NodeJS. Can I import all variables (including local) in NodeJS?

Do things right

TypeScript project should use CommonJS module system.

Add exports manually

If you can not change module system, you can add this at the end of your .ts file:

declare var module: { exports };
if (typeof module === "object" && module.exports)
    module.exports = mymodule;

Export several submodules

You can write this.mymodule1 = ... instead of var mymodule1 = ... . This mode works in both Node.js and browser.

Use "eval"

I can't change TypeScript file

If you can not change .ts file at all, use eval in dependent .js :

var fs = require("fs");
eval(fs.readFileSync("myTSModule.js", "utf8"));

mymodule.myCoolMethod("hello");

Use "runInContext"

Also you can isolate running context of ambient module by runInContext :

var context = vm.createContext();
vm.runInContext(code, context);
var mymodule = context.mymodule;

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