From 1c791dbd8e944bb5c7d9b253670ce8a54f76d8f2 Mon Sep 17 00:00:00 2001 From: Jonathan Kolberg Date: Fri, 5 May 2023 00:02:31 +0200 Subject: [PATCH] feat(node): allow executing esm compiled scripts (#10414) --- e2e/node/src/node.test.ts | 43 +++++++++++++++++++ .../node/node-with-require-overrides.ts | 4 +- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/e2e/node/src/node.test.ts b/e2e/node/src/node.test.ts index 609d7031d5..e8ed0ee3fd 100644 --- a/e2e/node/src/node.test.ts +++ b/e2e/node/src/node.test.ts @@ -21,6 +21,7 @@ import { tmpProjPath, uniq, updateFile, + updateJson, updateProjectConfig, } from '@nx/e2e/utils'; import { exec, execSync } from 'child_process'; @@ -230,6 +231,48 @@ describe('Node Applications', () => { expect(err).toBeFalsy(); } }, 120000); + + it('should be able to run ESM applications', async () => { + const esmapp = uniq('esmapp'); + + runCLI( + `generate @nrwl/node:app ${esmapp} --linter=eslint --framework=none --bundler=webpack` + ); + updateJson(`apps/${esmapp}/tsconfig.app.json`, (config) => { + config.module = 'esnext'; + config.target = 'es2020'; + return config; + }); + updateProjectConfig(esmapp, (config) => { + config.targets.build.options.outputFileName = 'main.mjs'; + config.targets.build.options.assets = []; + return config; + }); + updateFile( + `apps/${esmapp}/webpack.config.js`, + ` + const { composePlugins, withNx } = require('@nx/webpack'); + module.exports = composePlugins(withNx(), (config) => { + config.experiments = { + ...config.experiments, + outputModule: true, + topLevelAwait: true, + }; + config.output = { + path: config.output.path, + chunkFormat: 'module', + library: { type: 'module' } + } + return config; + }); + ` + ); + await runCLIAsync(`build ${esmapp}`); + const p = await runCommandUntil(`serve ${esmapp}`, (output) => { + return output.includes('Hello World'); + }); + p.kill(); + }, 300000); }); describe('Build Node apps', () => { diff --git a/packages/js/src/executors/node/node-with-require-overrides.ts b/packages/js/src/executors/node/node-with-require-overrides.ts index 6d152d5ada..f8583422c6 100644 --- a/packages/js/src/executors/node/node-with-require-overrides.ts +++ b/packages/js/src/executors/node/node-with-require-overrides.ts @@ -1,6 +1,8 @@ const Module = require('module'); const originalLoader = Module._load; +const dynamicImport = new Function('specifier', 'return import(specifier)'); + const mappings = JSON.parse(process.env.NX_MAPPINGS); const keys = Object.keys(mappings); const fileToRun = process.env.NX_FILE_TO_RUN; @@ -17,4 +19,4 @@ Module._load = function (request, parent) { } }; -require(fileToRun); +dynamicImport(fileToRun);