Why is typescript compiler omitting 'should.js

2019-07-21 14:08发布

问题:

I am facing a weird issue. In my (lets say) a.ts I have -

/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/should/should.d.ts" />

import should = require('should');

import something_else = require('../something-else');

Now when I compile using command -

tsc -m commonjs --outDir "./build" "src/test/a.ts"

My generated javascript is not having require for should -

/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/should/should.d.ts" />
var service_manager = require('../routes/service-manager');

This seems like a bug in typescript compiler, but I may be doing it incorrectly. Or if there is some workaround, please share.

回答1:

It does that because you are not using it. It will stick as soon as you you actually use the should variable. e.g.

/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/should/should.d.ts" />

import should = require('should');
var persist = should; 

Reason: It allows you to use type information on its own without taking a runtime dependency on require('should'). It also allows you to do lazy loading in AMD scenarios.



回答2:

As the comment by Eric Nicholson, just require without import.

require('should');
// use should

Besides, those reference path would be bundled at typings/tsd.d.ts by default and no need to write in individual file.