mirror of
https://github.com/nestjs/nest.git
synced 2026-02-21 23:11:44 +00:00
chore: add sample on how to use esm on cjs
This commit is contained in:
25
sample/34-using-esm-packages/.eslintrc.js
Normal file
25
sample/34-using-esm-packages/.eslintrc.js
Normal 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
56
sample/34-using-esm-packages/.gitignore
vendored
Normal 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
|
||||
4
sample/34-using-esm-packages/.prettierrc
Normal file
4
sample/34-using-esm-packages/.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
6
sample/34-using-esm-packages/README.md
Normal file
6
sample/34-using-esm-packages/README.md
Normal 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)
|
||||
8
sample/34-using-esm-packages/nest-cli.json
Normal file
8
sample/34-using-esm-packages/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
8630
sample/34-using-esm-packages/package-lock.json
generated
Normal file
8630
sample/34-using-esm-packages/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
75
sample/34-using-esm-packages/package.json
Normal file
75
sample/34-using-esm-packages/package.json
Normal 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"
|
||||
}
|
||||
}
|
||||
34
sample/34-using-esm-packages/src/app.controller.spec.ts
Normal file
34
sample/34-using-esm-packages/src/app.controller.spec.ts
Normal 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',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
12
sample/34-using-esm-packages/src/app.controller.ts
Normal file
12
sample/34-using-esm-packages/src/app.controller.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
27
sample/34-using-esm-packages/src/app.module.ts
Normal file
27
sample/34-using-esm-packages/src/app.module.ts
Normal 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');
|
||||
}
|
||||
}
|
||||
18
sample/34-using-esm-packages/src/app.service.ts
Normal file
18
sample/34-using-esm-packages/src/app.service.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
10
sample/34-using-esm-packages/src/import-esm-package.ts
Normal file
10
sample/34-using-esm-packages/src/import-esm-package.ts
Normal 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,
|
||||
);
|
||||
8
sample/34-using-esm-packages/src/main.ts
Normal file
8
sample/34-using-esm-packages/src/main.ts
Normal 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();
|
||||
10
sample/34-using-esm-packages/src/superjson.provider.ts
Normal file
10
sample/34-using-esm-packages/src/superjson.provider.ts
Normal 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'),
|
||||
};
|
||||
29
sample/34-using-esm-packages/test/app.e2e-spec.ts
Normal file
29
sample/34-using-esm-packages/test/app.e2e-spec.ts
Normal 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"]}}}',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
9
sample/34-using-esm-packages/test/jest-e2e.json
Normal file
9
sample/34-using-esm-packages/test/jest-e2e.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
4
sample/34-using-esm-packages/tsconfig.build.json
Normal file
4
sample/34-using-esm-packages/tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
21
sample/34-using-esm-packages/tsconfig.json
Normal file
21
sample/34-using-esm-packages/tsconfig.json
Normal 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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user