Skip to content

Instantly share code, notes, and snippets.

@doublecompile
Last active January 3, 2024 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doublecompile/324afb33b6038526705dfebb3b529e42 to your computer and use it in GitHub Desktop.
Save doublecompile/324afb33b6038526705dfebb3b529e42 to your computer and use it in GitHub Desktop.
TypeScript, Jest, ECMAScript Modules, and Projen
import { typescript, javascript } from "projen";
const project = new typescript.TypeScriptProject({
name: "template-typescript-esm",
defaultReleaseBranch: "main",
projenrcTs: true,
devDeps: ["@jest/globals"],
minNodeVersion: "18.0.0",
workflowNodeVersion: "18.18.2",
tsconfig: {
compilerOptions: {
moduleResolution: javascript.TypeScriptModuleResolution.NODE16,
module: "node16",
lib: ["DOM", "ES2022"],
target: "es2022",
},
},
jestOptions: {
jestConfig: {
extensionsToTreatAsEsm: [".ts"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
},
},
tsJestOptions: {
transformPattern: "^.+\\.ts$",
transformOptions: {
useESM: true,
},
},
});
project.package.file.addOverride("type", "module");
project.testTask.env("NODE_OPTIONS", "--experimental-vm-modules");
const [{ exec: projenrcCommand = "" }] = project.defaultTask!.steps;
project.defaultTask!.reset(projenrcCommand.replace("ts-node", "ts-node-esm"));
project.synth();

Projen + ECMAScript Modules (ESM) + TypeScript + Jest

How to configure Projen for an ESM library project on Node.js 18.

Many thanks to @danpetitt for the Gist he put together.

See the .projenrc.ts file below.

// This file exists at test/hello.test.ts
import { Hello } from "../src/index.js";
import { HELLO_WORLD } from "../src/text.js";
test("hello", () => {
expect(new Hello().sayHello()).toBe(HELLO_WORLD);
});
// This file exists at src/index.ts
import { HELLO_WORLD } from "./text.js";
export class Hello {
public sayHello(): string {
return HELLO_WORLD;
}
}
// This file exists at src/text.ts
export const HELLO_WORLD: string = "hello, world!";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment