'package.json' is not under 'rootDir'

前端 未结 4 1071
醉梦人生
醉梦人生 2020-11-29 10:56

I\'m trying to import package.json in my TypeScript application:

import packageJson from \'../package.json\';

My tsconfi

4条回答
  •  独厮守ぢ
    2020-11-29 11:40

    It is not possible for now. Typescript compiler try to keep your directory structure.

    For example, your project look like:

    src/
      shared/
        index.ts
      index.ts
    package.json
    tsconfig.json
    

    Your tsconfig.json contains:

    {
      "compilerOptions": {
        "outDir": "./build",
        "module": "commonjs",
        "target": "es6",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "noImplicitAny": true,
        "sourceMap": true,
        "resolveJsonModule": true,
        "esModuleInterop": true
      },
      "include": [
        "src/**/*"
      ]
    }
    

    As you see, the file does not include rootDir property, but when you call tsc command to compile the project, the output will look like:

    build/
      shared/
        index.js
      index.js
    

    The output does not contain src folder, because in my code, I just import and use inside src folder, like:

    src/index.ts

    import someName from './shared';
    

    then, build/index.js will look like:

    ...
    const shared_1 = __importDefault(require("./shared"));
    ...
    

    as you see - require("./shared"), this mean it working fine with build folder structure.

    Your "issue" appeared when you import a "outside" module

    import packageJson from '../package.json';
    

    So, what happen with "back" action - '../'? If you hope your output structure will be:

    build/
      package.json
      index.js
    

    then, how do they work with const packageJson = __importDefault(require("../package.json"));. Then Typescript compiler try to keep project structure:

    build/
      package.json
      src/
        index.js
    

    With a monorepo project, I think you need to create declaration files for each library, end then use references setting in the tsconfig file. Ex:

    1. In the ./lib01 folder, the lib import ./lib02 in their code. Tsconfig file will be like:
    {
      "compilerOptions": {
        "declarationDir": "dist",
        "rootDir": "src"
      },
      "include": ["src/**/*"],
      "references": [ // here
        {
          "path": "../lib02"
        }
      ]
    }
    
    1. lib02's tsconfig.json
     {
       "compilerOptions": {
        "declarationDir": "dist",
        "rootDir": "src",
        "composite": true // importance.
      }
     }
    

提交回复
热议问题