如何在 TypeScript 中默认导入我所有的规范文件?

How to have default imports for all my spec files in TypeScript?

这是一个非常简单的规范文件,用于对 TypeScript + React 应用程序进行单元测试:

import * as React from "react"; // COMMON

import * as chai from "chai"; // COMMON
import * as chaiEnzyme from "chai-enzyme" // COMMON
import * as sinon from "sinon"; // COMMON
import * as sinonChai from "sinon-chai"; // COMMON

import { expect } from "chai"; // COMMON
import { shallow } from "enzyme"; // COMMON

import Hello from "./Hello";

describe("Hello", () => {

    chai.use(chaiEnzyme()); // COMMON
    chai.use(sinonChai); // COMMON

    let hello = shallow(<Hello name="Willson" />);

    it("should render correctly", () => {
        expect(hello).to.have.tagName("div");
    });

    it("should have correct prop values", () => {
        expect(hello).to.have.text("Hello, Willson");
    });

});

我看到自己在每个规范文件中都使用了带有 // COMMON 的行。 是否有一种 TypeScript 方法可以在我的所有匹配的文件上默认执行此操作:/Spec\.(ts|tsx)/?

你可以做一件事来稍微缓解这个问题。

首先像这样创建您的 common.ts

//Collect and re-export all of your COMMON imports

import * as React from "react"; 
export {React};

import * as ReactDOM from 'react-dom';
export {ReactDOM};

//More import/exports goes here

然后在你的规范文件中你只需要导入一个:

import * as Common from './common';

稍后在规范文件中,您可以像这样使用它们:

private static childContextTypes = 
{
    extender: Common.React.PropTypes.object,
    form: Common.React.PropTypes.object
}

希望这对您有所帮助。