'package.json' is not under 'rootDir'

前端 未结 4 1079
醉梦人生
醉梦人生 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

    We can set resolveJsonModule to false and declare a module for *.json inside typings.d.ts which will require JSON files as modules and it will generate files without any directory structure inside the dist directory.

    Monorepo directory structure

    monorepo\
    ├─ app\
    │  ├─ src\
    │  │  └─ index.ts
    │  ├─ package.json
    │  ├─ tsconfig.json
    │  └─ typings.d.ts
    └─ lib\
       └─ package.json
    

    app/typings.d.ts

    declare module "*.json";
    

    app/src/index.ts

    // Import from app/package.json
    import appPackageJson from '../package.json';
    
    // Import from lib/package.json
    import libPackageJson from '../../lib/package.json';
    
    export function run(): void {
      console.log(`App name "${appPackageJson.name}" with version ${appPackageJson.version}`);
      console.log(`Lib name "${libPackageJson.name}" with version ${libPackageJson.version}`);  
    }
    
    run();
    

    package.json contents

    app/package.json
    {
      "name": "my-app",
      "version": "0.0.1",
      ...
    {
    
    lib/package.json
    {
      "name": "my-lib",
      "version": "1.0.1",
      ...
    }
    

    Now if we compile the project using tsc, we'll get the following dist directory structure:

    app\
    └─ dist\
       ├─ index.d.ts
       └─ index.js
    

    And if we run it using node ./dist, we'll get the output from both app and lib package.json information:

    $ node ./dist
    App name "my-app" with version 0.0.1
    Lib name "my-lib" with version 1.0.1
    

    You can find the project repository here: https://github.com/clytras/typescript-monorepo

提交回复
热议问题