I'm working on a library for express called expresskit. The goal is to setup some organization standards for a node rest server so there is a specific way I'd like it to work.
For one, instead of having a tangle of require I want to use es6 explicit imports. Like this-
import ExpressKit from 'expresskit';
ExpressKit.start({
port: 8000
});
I want to do this instead of var ExpressKit = require('expresskit'); for a number of reasons. First, the IDE knows what the import is, while the require loses any intellisense. I don't want to use references because I want to avoid having /// <reference/> tags in all of my files. Second, with es6 explicit imports you shouldn't need namespaces/modules since the path acts as the namespace itselfs, like com.org.foo.bar. Here is an example of a route with expresskit-
import Route from 'expresskit/route';
import {Param} from 'expresskit/property';
import User from './';
export default class UserRouter {
@Route('GET', '/user/:id')
public static getUser(@Param('id') userId: number,) {
return new User();
}
}
You know exactly what's being used an where it comes from. There is no global-scoped objects or referencing via the expresskit namespace. The alternative would be something like this-
/// <reference path="../node_modules/expresskit/expresskit.d.ts"/>
var ExpressKit = require('expresskit');
var Route = ExpressKit.Route;
var Param = ExpressKit.Param;
import User from './';
export default class UserRouter {
@Route('GET', '/user/:id')
public static getUser(@Param('id') userId: number,) {
return new User();
}
}
So the problem I'm having and the reason why I can't get the es6 explicit imports to work properly, is when the typescript is compiled via tsc. Javascript is built to a bld directory. Since you are referencing expresskit source via es6 imports, it is also building this to bld. The result looks like this-
/
bld/
node_modules/
expresskit/
...
user/
index.js
router.js
index.js
node_modules/
expresskit/
...
express/
...
body-parser/
...
user/
index.ts
router.ts
index.ts
tsconfig.json
Now when I run the build project by running node bld/index.js I get the error-
Error: Cannot find module 'express'
The reason for this is because expresskit as bld/node_modules/expresskit/index.js is calling require('express'), which it looking for express in bld/node_modules/ when it's actual location is in node_modules/.
I don't want to copy everything from node_modules/ to bld/node_modules/ and if I did I think the usefulness of the library would be questionable.
What I'm about to try to do is compile to a single file using systemjs instead of commonjs. This will require a custom build script that injects var System = require('systemjs') to the top of the built file. But this may be the least invasive of my options. Is this the way to go?
So how can I have my cake and eat it too?
node_modulesdirectories? You can movebld/node_modulestonode_modules. nodejs.org/api/…