简体   繁体   中英

What is the best setting for tsconfig.json working with node.js modules?

So far I have 2 files in "./src": index.ts and setConfig.ts . Both import 'fs' and 'path' like this:

const fs = require('fs');
const path = require('path');

... and that's what Typescript obviously doesn't like; when compiling it says:

src/index.ts:1:7 - error TS2451: Cannot redeclare block-scoped variable 'fs'.

1 const fs = require('fs');
        ~~

  src/setConfig.ts:1:7
    1 const fs = require('fs');
            ~~
    'fs' was also declared here.

src/index.ts:2:7 - error TS2451: Cannot redeclare block-scoped variable 'path'.

2 const path = require('path');
        ~~~~

  src/setConfig.ts:2:7
    2 const path = require('path');
            ~~~~
    'path' was also declared here.

src/setConfig.ts:1:7 - error TS2451: Cannot redeclare block-scoped variable 'fs'.

1 const fs = require('fs');
        ~~

  src/index.ts:1:7
    1 const fs = require('fs');
            ~~
    'fs' was also declared here.

src/setConfig.ts:2:7 - error TS2451: Cannot redeclare block-scoped variable 'path'.

2 const path = require('path');
        ~~~~

  src/index.ts:2:7
    2 const path = require('path');
            ~~~~
    'path' was also declared here.


Found 4 errors.

But when I leave it out in setConfig.ts node complains that it doesn't know 'fs'....

My tsconfig.json looks like this:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "./dist/",
    "rootDir": "./src/", 
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true
  }
}

So, what else do I have to add or do to make my compiled JavaScript work properly?

Adding exports in your setConfig.ts module should solve the problem.

// setConfig.ts
export default {
  // your exports
};
// Or
export function foo() {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM