Skip to content

Commit f2d8296

Browse files
authored
inject shim for cjs dependencies (#951)
* inject shim for cjs require * add filename and dirname to cjs shim
1 parent 4c1485a commit f2d8296

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

.changeset/lucky-lizards-tan.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@aws-amplify/backend-function': patch
3+
---
4+
5+
Inject shim for cjs require for functions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { createRequire } from 'node:module';
2+
import path from 'node:path';
3+
import url from 'node:url';
4+
global.require = createRequire(import.meta.url);
5+
global.__filename = url.fileURLToPath(import.meta.url);
6+
global.__dirname = path.dirname(__filename);

packages/backend-function/src/factory.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import * as path from 'path';
1313
import { getCallerDirectory } from './get_caller_directory.js';
1414
import { Duration } from 'aws-cdk-lib';
1515
import { Runtime } from 'aws-cdk-lib/aws-lambda';
16-
1716
import fs from 'fs';
1817
import { createRequire } from 'module';
1918
import { FunctionEnvironmentTranslator } from './function_env_translator.js';
@@ -246,6 +245,8 @@ class AmplifyFunction
246245
.replaceAll('\r', '')
247246
.split('//#')[0]; // remove source map
248247

248+
const cjsShimRequire = require.resolve('./cjs_shim');
249+
249250
const functionLambda = new NodejsFunction(scope, `${id}-lambda`, {
250251
entry: props.entry,
251252
environment: environmentRecord as { [key: string]: string }, // for some reason TS can't figure out that this is the same as Record<string, string>
@@ -255,6 +256,7 @@ class AmplifyFunction
255256
bundling: {
256257
banner: bannerCode,
257258
format: OutputFormat.ESM,
259+
inject: [cjsShimRequire], // replace require to fix dynamic require errors with cjs
258260
},
259261
});
260262

0 commit comments

Comments
 (0)