AWS CDK2 Synth Cannot Find Module - NPM Linked Peer Dependency

Viewed 73

I have an AWS CDK v2 project and can successfully synth when I import a local npm package by adding the following to package.json:

"@my/constructs": "file:../my/dist/packages/constructs"

This package resides in a separate Nx monorepo.

I have another package in the Nx monorepo "@my/coolthing"

When I import "@my/coolthing" into "@my/constructs" I get an AWS CDK synth error: Cannot find module '@my/coolthing'.

The "@my/constructs" package.json lists "@my/coolthing" correctly in peerDependencies i.e.

"peerDependencies": {
    "@my/coolthing": "1.0.0"
}

How can I get the CDK to synth successfully?

Things I've tried:

  • Manually copying the "@my/coolthing" directory to the CDK node_modules folder.
  • Publishing "@my/coolthing" to NPM and doing an NPM install in the CDK project.
1 Answers

The core problem was difficult to determine due to the complexity of both the CDK and Nx frameworks but I think it is simply a known NPM bug as described here:

https://www.chevtek.io/you-can-finally-npm-link-packages-that-contain-peer-dependencies/

Note that this bug only occurs because npm modules are linked. There was no error when I published these NPM modules.

So Nx creates a simple NPM package with peer dependencies. An npm install in the CDK project does NOT install peer dependencies and instead expects it to be already installed in the project.

But even when we install @my/coolthing in the CDK project.json we still get the "Cannot find module '@my/coolthing'" error.

"dependencies": {
    "@my/constructs": "file:../my/dist/packages/constructs"
    "@my/coolthing": "file:../my/dist/packages/coolthing"
    ...
}

In a node app, this bug is apparently resolved by using the preserve-symlinks param e.g.

node --preserve-symlinks app.js

But I can find no such command supported by the AWS CDK v2.

But I noticed that if I copied @my/coolthing files to the following Nx project path then CDK synth worked:

/my/dist/@my/coolthing

So CDK synth causes node to walk up the Nx directory tree starting from the @my/constructs location looking for a node_modules folder with @my/coolthing.

The best workaround I could come up with is to create a package.json in Nx project /my/dist:

{
    "name": "dist",
    "description": "Work around for CDK org project cannot find peer dependency module.",
    "dependencies": {
        "@my/coolthing": "file:../libs/coolthing",
    }
}

So instead of copying files this simply symlnks files. Now a CDK synth is successful and whenever we build @my/coolthing the latest version is in node_modules.

Related