LernaJS Typescript cannot find module

J G picture J G · Jun 10, 2018 · Viewed 12.4k times · Source

I'm trying to use LernaJS with typescript and I have some problems. When I try to run my package-1 which has package-2 as dependency I get the error:

    module.js:549
        throw err;
        ^
    
    Error: Cannot find module 'package-2'
        at Function.Module._resolveFilename (module.js:547:15)
        at Function.Module._load (module.js:474:25)
        at Module.require (module.js:596:17)
        at require (internal/module.js:11:18)
        at Object. (/home/gabriel/Documentos/projetos/nodejs/lerna-t2/packages/package-1/dist/index.js:3:19)
        at Module._compile (module.js:652:30)
        at Object.Module._extensions..js (module.js:663:10)
        at Module.load (module.js:565:32)
        at tryModuleLoad (module.js:505:12)
        at Function.Module._load (module.js:497:3)

I've followed the following steps:

  1. I've created a directory and ran the command 'lerna init'
  2. I've created 2 folders inside (package-1, package-2) 'packages' folder
    .
    ├── lerna.json
    ├── node_modules
    ├── package.json
    ├── package-lock.json
    └── packages
        ├── package-1
        └── package-2
  1. I've ran 'npm init' in both (package-1, package-2)
  2. I've created a basic 'tsconfig.json' in both packages:
    {
        "compilerOptions": {
            "outDir": "dist",
            "target": "es5",
            "module": "commonjs"
        }
    }
  1. I've ran 'lerna bootstrap' in the root folder
  2. I've use 'lerna add package-2 --scope=package-1'
  3. I've ran also 'npm i' in root folder, package-1 and package-2
  4. I've ran 'tsc -w' in package-1 and package-2 and 'node dist/index.js' in package-1

FILE TREE

My 'package-1' file tree:


    .
    ├── dist
    │   └── index.js
    ├── index.ts
    ├── node_modules
    │   ├── package-2 -> ../../package-2
    │   └── typescript
    ├── package.json
    ├── package-lock.json
    └── tsconfig.json

My 'package-2' file tree:


    .
    ├── dist
    │   ├── index.js
    │   └── lib
    │       └── teste.js
    ├── index.ts
    ├── lib
    │   └── teste.ts
    ├── package.json
    ├── package-lock.json
    └── tsconfig.json

CODE

package-1:

  • index.ts:

    import { Teste } from 'package-2'
    
    new Teste().printHello()

package-2:

  • lib/teste.ts:

    export class Teste {
    
        printHello() {
            console.log('Hello!')
        }
    
    }

  • index.ts:

    export { Teste } from './lib/teste'

Answer

lajtmaN picture lajtmaN · Jun 12, 2018

Please ensure you have defined main in your package.json in (at least project-2). I assume the name field in package.json (for project-2) is project-2.

Main should link to dist/index.js