Skip to content

Commit e41aa66

Browse files
committed
adding support for .cjs file extensions for user function
Within ES modules (type is module inside package.json), if you try to either: ``` require('file') require('file.js') ``` it does not allow that as imports should be used within ES modules. The only way to use require() is to explicitly require `.cjs` file which explicitly insidicates that path is a CommonJS file, not ESM: ``` require('file.cjs') ``` This change allows to require .cjs files when a user function is being searched. I would imagine eventually this library would need to fully support ES modules as per aws#44 however this diff will allow people to use lambdas within ES modules if they have .cjs lambda files.
1 parent 5ba533b commit e41aa66

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

src/utils/UserFunction.ts

+12-6
Original file line numberDiff line numberDiff line change
@@ -58,13 +58,18 @@ function _resolveHandler(object: any, nestedProperty: string): any {
5858
}
5959

6060
/**
61-
* Verify that the provided path can be loaded as a file per:
61+
* Try to get path to a file path if it can loaded as a file per:
6262
* https://nodejs.org/dist/latest-v10.x/docs/api/modules.html#modules_all_together
6363
* @param string - the fully resolved file path to the module
64-
* @return bool
64+
* @return string
6565
*/
66-
function _canLoadAsFile(modulePath: string): boolean {
67-
return fs.existsSync(modulePath) || fs.existsSync(modulePath + ".js");
66+
function _getLoadAsFilePath(modulePath: string): string {
67+
const paths = [modulePath + ".cjs", modulePath + ".js", modulePath];
68+
for (const path of paths) {
69+
if (fs.existsSync(path)) {
70+
return path;
71+
}
72+
}
6873
}
6974

7075
/**
@@ -74,8 +79,9 @@ function _canLoadAsFile(modulePath: string): boolean {
7479
*/
7580
function _tryRequire(appRoot: string, moduleRoot: string, module: string): any {
7681
const lambdaStylePath = path.resolve(appRoot, moduleRoot, module);
77-
if (_canLoadAsFile(lambdaStylePath)) {
78-
return require(lambdaStylePath);
82+
const filePath = _getLoadAsFilePath(lambdaStylePath);
83+
if (filePath) {
84+
return require(filePath);
7985
} else {
8086
// Why not just require(module)?
8187
// Because require() is relative to __dirname, not process.cwd()

0 commit comments

Comments
 (0)