Search code examples
node.jsamazon-web-servicesaws-cdkes6-modules

Unable to deploy a .mjs file using CDK


I'm trying to create a Nodejs Lambda project locally in vscode, which I'm going to deploy using CDK. I start by running

cdk init app --language javascript

At some point in my development I'm going to want to use EC6 modules, so I will need to add "type":"module" into my package.json

If I run cdk synth now, I start to get these errors:

file:///E:/Code/Github/VBG/dnclistimporter/bin/dnclistimporter.js:3 const cdk = require('aws-cdk-lib'); ^

ReferenceError: require is not defined in ES module scope, you can use import instead This file is being treated as an ES module because it has a '.js' file extension and 'E:\Code\Github\VBG\dnclistimporter\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

Fair enough, so I change my requires to imports, so in my importer.js file this

const cdk = require('aws-cdk-lib'); const { DnclistimporterStack } = require('../lib/dnclistimporter-stack');

const app = new cdk.App(); new DnclistimporterStack(app, 'DnclistimporterStack', {});

becomes this

import * as cdk from 'aws-cdk-lib'; import { DncListImporterStack } from '../lib/dnclistimporter-stack'; const app = new cdk.App(); new DnclistimporterStack(app, 'DnclistimporterStack', {});

and now I'm getting the following error message

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'E:\Code\Github\VBG\dnclistimporter\lib\dnclistimporter-stack' imported from E:\Code\Github\VBG\dnclistimporter\bin\dnclistimporter.js

It's the same code, just imported using import not require, but it doesn't find the module. I rename the .js to .mjs and now it gives

SyntaxError: The requested module '../lib/dnclistimporter-stack.mjs' does not provide an export named 'DncListImporterStack'

It's the same code, just had the file renamed to .mjs:

const { Stack, Duration } = require('aws-cdk-lib'); class DnclistimporterStack extends Stack {

constructor(scope, id, props) { super(scope, id, props); } }

module.exports = { DnclistimporterStack }

I change the require to an import:

import { Stack } from 'aws-cdk-lib'

class DnclistimporterStack extends Stack {
 
  constructor(scope, id, props) {
    super(scope, id, props);

  }
}

module.exports = { DnclistimporterStack }

But get the same error. What am I doing wrong and is there a better way of setting up an AWS Lambda project (apart from an AWS SAM app which requires docker and I can't install that because I'm working on a VM)


Solution

  • You have a typo. Perhaps that's your issue.

    You are exporting "DnclistimporterStack" but are importing "DncListImporterStack"