Search code examples
node.jstypescriptlerna

Module not found while importing nested module


Suppose that we have package1 and package2. If package2 tries to import package1 module we get an error that says module not found. Import looks like import { ... } from 'package1/styles'. Keep in mind that imports like import { ... } from 'package1' works. In my opinion these import issues are caused because lerna incorrectly links folders. I would expect that node_modules of package2 should contain only package1/dist instead of package1. How these import issues should be solved?

Relevant package1 files below.

package.json:

...
"main": "./dist/index.js",
"files": ["dist"]
...
tsconfig.json:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": false,
    "declaration": true,
    "jsx": "react",
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}


After we run lerna run build we get following directory structure:

packages/package2/node_modules/package1/
├── dist
│  ├── index.d.ts
│  ├── index.js
│  └── styles
│     ├── index.d.ts
│     └── index.js
├── node_modules
├── package-lock.json
├── package.json
├── src
│  ├── index.ts
│  └── styles
│     └── index.ts
├── tsconfig.json
└── webpack.config.js

Solution

  • tsconfig.json should have paths that would resolve module dependencies like:

    ...
        "baseUrl": "./packages",
        "paths": {
          "package1": ["./package1/src"],
          "package1/*": ["./package1/src/*"]
        }
    ...