Matthew Layton
Matthew Layton

Reputation: 42390

TypeScript - Compiling to single files

I am currently writing a project that has some very long source files, which is great for imports but not so great for maintenance; for example:

/main/core.ts

export type Foo { ... }

export interface Bar { ... }

export class Baz { ... }

/main/data.ts

import { Foo, Bar } from "core";

const x: Foo = ...;
export class BarImpl implements Bar { ... }

Currently these files compile to:

As mentioned, it's a bit of a maintenance nightmare, with source files getting longer and longer as more features are added. What I'd like to do is split these out into their own source files under a new directory; for example:

/main/core/foo.ts

export type Foo { ... }

/main/core/bar.ts

export interface Bar { ... }

/main/core/baz.ts

export class Baz { ... }

I can do this, but it has a knock on effect with imports; for example:

/main/data/barimpl.ts

import { Foo } from "core/foo";
import { Bar } from "core/bar";

const x: Foo = ...
export class BarImpl implements Bar { ... }

Is it possible to:

  1. Split /main/core.ts into /main/core/foo.ts etc. and still compile them to /dist/core.js etc.?
  2. Maintain imports like import { Foo, Bar } from "core" rather than having to split imports by file?

Upvotes: 1

Views: 55

Answers (1)

Paul
Paul

Reputation: 1022

You could add a barrel to your codebase.

// main/core/index.ts
export * from './foo';
export * from './bar';
export * from './baz';
// Example consumer
import { Foo, Bar, Baz } from 'core';

Upvotes: 1

Related Questions