How to share code between TypeScript projects?

后端 未结 5 758
猫巷女王i
猫巷女王i 2020-12-12 19:11

Let\'s say I have two projects with following file structure

/my-projects/

  /project-a/
    lib.ts
    app.ts
    tsconfig.json

  /project-b/
    app.ts           


        
5条回答
  •  情书的邮戳
    2020-12-12 19:30

    In a similar scenario, where I also wanted to avoid the overhead of having to perform an NPM release, I went for the following structure (after lots of trial and error and failed attempts):

    /my-projects/
    
      /node_modules/
        /my-lib/
          lib.ts
          tsconfig.json
          package.json
    
      /project-a/
        app.ts
        tsconfig.json
    
      /project-b/
        app.ts         
        tsconfig.json
    

    The central idea is to move the shared stuff to a node_modules directory above the individual projects (this exploits NPMs loading mechanism, which would start looking for dependencies in the current directory and then move upwards).

    So, project-a and project-b can now access the lib simply via import { Whatever } from 'my-lib'.

    Notes:

    1. In my case, my-lib is actually only for shared typings (i.e. .d.ts files within a lib subdirectory). This means, I do not explicitly need to build my-lib and my my-lib/package.json looks as follows:

      {
        "name": "my-types",
        "version": "0.0.0",
        "private": true,
        "types": "lib/index"
      }
      
    2. In case my-lib contains runnable code, you’ll obviously need to build my-lib, so that .js files are generated, and add a "main" property to the package.json which exposes the main .js file.

    3. Most important: Despite its name, /my-projects/node_modules only contains custom code, no installed dependencies (they are actually in the individual projects project-a/node_modules and project-b/node_modules). This means, there’s an explicit git ignore setting, which un-ignores the /node_modules directory from being committed.

    Is this a clean solution? Probably not not. Did it solve my issue? Yes. Am I happy to hear about improvement suggestions? Absolutely!

提交回复
热议问题