I'm working on a node.js/express project that I am using typescript in. I don't have any problems importing things but I have to use the following format which is ugly/not scalable
import MyModule = require("../../ModuleFolder/MyModule");
Assuming my module looked like this
export module MyModule
{
export function doStuff():void
{
//do stuff here
}
}
I can't figure out how to pull in modules and classes without specifying the path. Ideally I would like to be able to pull this in like
import MyModule = require("MyModule");
Is there something I can do to make this possible or improve this implementation?
Update: Ultimately I ended up using modules for this, which works very well.
The best way to do this is to make NPM modules (they can be private, just don't npm publish
them) and put them into your own node_modules
folder. Since using require()
automatically looks for these folders , you can leverage this to your side in such a way as this...
The module : ./node_modules/MyModule/index.ts
export module MyModule
{
export function doStuff():void
{
//do stuff here
}
}
You can run npm init
within that ./node_modules/MyModule
folder to create the package.json
file.
The main file : ./src/some/other/folder/or/elsewhere/main.ts
import MyModule = require('MyModule');
if you specify a script in
var Name = require ('name')
than nodeJS automatically looks into node_modules for the directory 'name' and the module definition inside. If you have your modules elsewhere then you need to specify path. Alternatively create symbolic link in node_modules
pointing to your module directory.
Creating custom local module directly in the node_modules is not recommended as the node_modules is not supposed to be edited, and everything in it can get deleted during a project reinstall. Instead, create a local module and include it in the package.json just like any other library dependencies.
Within the project root folder, create a folder and file at MyModule/index.ts with the following.
export module MyModule
{
export function doStuff():void
{
//do stuff here
}
}
cd into the MyModule folder, run the npm init command, when prompted, just press enter.
npm init
cd back to the project root folder, and run this command to add the local module to the package.json file.
npm install --save MyModule
Import the module anywhere in the project with this.
import MyModule = require('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.