chore: add sample on how to use esm on cjs

This commit is contained in:
Micael Levi L. Cavalcante
2024-09-28 12:24:44 -04:00
parent 9825529f40
commit 0dafaaa0b9
18 changed files with 8986 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

56
sample/34-using-esm-packages/.gitignore vendored Normal file
View File

@@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View File

@@ -0,0 +1,6 @@
## About using ESM with Jest
We are using the `--experimental-vm-modules` NodeJS v18 flag as explained at https://jestjs.io/docs/ecmascript-modules
You can see how to mock an ESM package at [`app.controller.spec.ts`](./src/app.controller.spec.ts)
You can see how that the real import of an ESM package is working at [`app.e2e-spec.ts`](./test/app.e2e-spec.ts)

View File

@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,75 @@
{
"name": "34-using-esm-packages",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"type": "commonjs",
"engines": {
"node": ">=18.8"
},
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest",
"test:watch": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest --watch",
"test:cov": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest --coverage",
"test:debug": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "10.x",
"@nestjs/core": "10.x",
"@nestjs/platform-express": "10.x",
"delay": "6.x",
"reflect-metadata": "0.2.0",
"rxjs": "7.x",
"superjson": "2.x"
},
"devDependencies": {
"@nestjs/cli": "10.x",
"@nestjs/schematics": "10.x",
"@nestjs/testing": "10.x",
"@types/express": "4.x",
"@types/jest": "29.x",
"@types/node": "20.x",
"@types/supertest": "6.x",
"@typescript-eslint/eslint-plugin": "8.x",
"@typescript-eslint/parser": "8.x",
"eslint": "8.x",
"eslint-config-prettier": "9.x",
"eslint-plugin-prettier": "5.x",
"jest": "29.5.0",
"prettier": "3.x",
"source-map-support": "0.5.21",
"supertest": "7.x",
"ts-jest": "29.x",
"ts-loader": "9.x",
"ts-node": "10.x",
"tsconfig-paths": "4.x",
"typescript": "5.5.x"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@@ -0,0 +1,34 @@
// NOTE: This tests nothing, it's just to show how to mock an ESM package
import { jest } from '@jest/globals';
// We will test the mocking feature from Jest to mock the `superjson` package for testing purposes
// We must call this before loading the module!
jest.unstable_mockModule('superjson', () => ({
stringify: () => 'noop',
}));
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { superJSONProvider } from './superjson.provider';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [superJSONProvider, AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return the stub object', () => {
expect(appController.getHello()).toEqual({
jsonString: 'noop',
});
});
});
});

View File

@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello() {
return this.appService.getHello();
}
}

View File

@@ -0,0 +1,27 @@
import { Module, OnModuleInit } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { superJSONProvider } from './superjson.provider';
import { importEsmPackage } from './import-esm-package';
@Module({
imports: [],
controllers: [AppController],
providers: [
superJSONProvider, // One way to load the ESM package is turning it into a custom provider
AppService,
],
})
export class AppModule implements OnModuleInit {
// This is just to test the 'delay' ESM-only package
async onModuleInit() {
// Another way to load the ESM package is using our 'import' function directly when we need to use it
const delay =
await importEsmPackage<typeof import('delay').default>('delay');
console.time('delay');
await delay(1_000);
console.timeEnd('delay');
}
}

View File

@@ -0,0 +1,18 @@
import { Inject, Injectable } from '@nestjs/common';
import { superJSONProvider, SuperJSON } from './superjson.provider';
@Injectable()
export class AppService {
constructor(
@Inject(superJSONProvider.provide)
private readonly superjson: SuperJSON,
) {}
getHello() {
const jsonString = this.superjson.stringify({ big: 10n });
return {
jsonString,
};
}
}

View File

@@ -0,0 +1,10 @@
/**
* This is the same as `import()` expression that is supposed to load ESM packages while
* preventing TypeScript from transpiling the import statement into `require()`.
*/
export const importEsmPackage = async <ReturnType>(
packageName: string,
): Promise<ReturnType> =>
new Function(`return import('${packageName}')`)().then(
(loadedModule: unknown) => loadedModule['default'] ?? loadedModule,
);

View File

@@ -0,0 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();

View File

@@ -0,0 +1,10 @@
import { FactoryProvider } from '@nestjs/common';
import { importEsmPackage } from './import-esm-package';
// We must expose only the type definition!
export type { SuperJSON } from 'superjson';
export const superJSONProvider: FactoryProvider = {
provide: 'SuperJSON',
useFactory: () => importEsmPackage('superjson'),
};

View File

@@ -0,0 +1,29 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect(
JSON.stringify({
jsonString:
'{"json":{"big":"10"},"meta":{"values":{"big":["bigint"]}}}',
}),
);
});
});

View File

@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}