使用 TypeScript 导入 'global' 个模块

Import 'global' modules with TypeScript

我正在使用 Mocha 和 TypeScript 编写测试...这是一个简单的示例:

import {assert} from 'chai';
import Greeting from '../../../src/component/greeting/greeting';

describe('Greeting component', function () {
    it('should greet correctly', function () {
        let greeting = new Greeting();
        assert(greeting.greeting === 'Hello World', 'should express the correct greeting');
    });
});

我可以看到这些编译正确。我将它们输出为 common-js 模块并使用 system-js 作为浏览器内加载器。

System.import('component/greeting/greetingSpec.js')
    .catch(console.log.bind(console))
    .then(function() {
        mocha.run();
    })

我想创建一个列出所有 'spec' 个文件的文件:

import * as greeting from './greeting/greetingSpec';
import * as foo from './greeting/fooSpec';

但是 TypeScript 编译器可以看到这些导入未被使用,因此不会将它们包含在 JS 输出中。

如何为可以通过 system-js 加载的测试定义单个 'entry point'?

您的代码

import * as greeting from './greeting/greetingSpec';
import * as foo from './greeting/fooSpec';

However the TypeScript compiler can see that these imports are unused, so doesn't include them in the JS output.

这是一项功能,支持例如延迟加载:https://basarat.gitbooks.io/typescript/content/docs/project/external-modules.html

解决方法:

import * as greeting from './greeting/greetingSpec';
import * as foo from './greeting/fooSpec';
// use the imports in a dummy fashion to enforce that they get loaded
let _greeting = greeting;
let _foo = foo;

I do this all the time here :-)

尝试仅使用副作用 import:

import './greeting/greetingSpec';
import './greeting/fooSpec';

这不会被省略。有关详细信息,请参阅 this discussion