9

I have a rather large project A using Node and Typescript. In project A I have a lot of different modules that I would like to reuse in another project B.

Therefore I have built the project A with this tsconfig.json:

{
    "compilerOptions": {
        "target": "es2017",
        "module": "commonjs",
        "declaration": true,
        "outDir": "./dist",
        "sourceMap": true,
        "strict": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "typeRoots": ["./node_modules/@types", "./modules/@types"]
    },
    "exclude": ["node_modules"]
}

So all the files are built into the /dist folder this way:

  • dist
    • moduleA.js
    • moduleA.map
    • moduleA.d.ts
    • moduleB.js
    • moduleB.map
    • moduleB.d.ts
    • ....

To use these moduleA and moduleB in another project, I add the following to the package.json in Project A:

    "name": "projectA",
    "version": "1.0.0",
    "description": "...",
    "main": "dist/moduleA.js",
    "typings": "dist/moduleA.d.ts",

I use yarn workspaces to access Project A as a package in Project B. But problem is that I can only access moduleA, when using import {ModuleA} from 'projectA' in my new project B? So how can I access more modules from ProjectA?

tk421
  • 5,775
  • 6
  • 23
  • 34
Jolle
  • 1,336
  • 5
  • 24
  • 36

3 Answers3

9

Would simply consolidating all exports in one index.ts do the trick for you?

package.json (projectA):

{
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
  ...
}

index.ts (projectA):

// Adjust the relative import paths 
// and identifiers to your structure
export { ModuleA } from "./moduleA";
export { ModuleB } from "./moduleB";

Some module in projectB:

import {ModuleA, ModuleB} from 'projectA'
ford04
  • 66,267
  • 20
  • 199
  • 171
  • see also this answer: https://stackoverflow.com/questions/34072598/es6-exporting-importing-in-index-file – ford04 Aug 17 '19 at 11:56
  • 4
    This does not answer the question. What if you don't want modules included or want to deal with a larger file size? – mellis481 May 31 '20 at 22:01
7

I believe what you are looking for is: https://nodejs.org/api/packages.html#packages_package_entry_points

Not clear if TypeScript currently supports it or not: https://github.com/microsoft/TypeScript/issues/33079

It does appear you can work around it though with something like this in your package.json:

{
    ...

    "main": "./dist/index.js",
    "types": "./dist/index.d.ts",
    "typesVersions": {
        "*": {
          "dist/index.d.ts": [ "dist/index.d.ts" ],
          "*": [ "dist/*" ]
        }
      },
    "exports": {
        ".": "./dist/index.js",
        "./": "./dist/"
    },

    ...
}
-1

try compilerOptions.moduleResolution = 'node16' in your tsconfig.json

Here's a link to the documentation https://www.typescriptlang.org/tsconfig#moduleResolution

QuantumLicht
  • 2,103
  • 3
  • 23
  • 32
pykiss
  • 949
  • 12
  • 15