【问题标题】:What is the best setting for tsconfig.json working with node.js modules?tsconfig.json 与 node.js 模块一起使用的最佳设置是什么?
【发布时间】:2020-08-15 21:20:10
【问题描述】:

到目前为止,我在“./src”中有 2 个文件:index.tssetConfig.ts。 像这样导入'fs'和'path':

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

... 这显然是 Typescript 不喜欢的;编译时说:

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.

但是当我把它放在setConfig.ts 中时,节点抱怨它不知道'fs'......

我的tsconfig.json 看起来像这样:

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

那么,我还需要添加什么或做什么才能使我编译的 JavaScript 正常工作?

【问题讨论】:

    标签: javascript node.js typescript node-modules commonjs


    【解决方案1】:

    setConfig.ts 模块中添加导出应该可以解决问题。

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

    【讨论】:

    • 问题解决了,谢谢!我使用了module.exports = foo() {}const setConfig() = require("./setConfig"),它们以前在 js 中工作,但显然不再在 ts 中......
    猜你喜欢
    • 2012-04-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 2011-08-14
    • 2011-04-11
    • 1970-01-01
    相关资源
    最近更新 更多