javascript - tsconfig.json 与 Node.js 模块一起使用的最佳设置是什么?

标签 javascript node.js typescript node-modules commonjs

到目前为止,我在“./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 Node 中时,它会提示它不知道“fs”....

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

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

那么,我还需要添加或执行哪些操作才能使编译后的 JavaScript 正常工作?

最佳答案

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

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

关于javascript - tsconfig.json 与 Node.js 模块一起使用的最佳设置是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61541569/

相关文章:

javascript - NestJS 在非模块文件中注入(inject)模块服务

javascript - 查找数组中 100 个最新值的值

javascript - 如何在工厂服务中定义的ng-click中调用函数

javascript - javascript : when nested function is defined or executed? 闭包什么时候捕获变量值(在外部函数中定义)

mysql - LIKE SQL 语法错误

image - 从 dataDirectory 文件路径设置为 img 的 src

javascript - Selenium:如何跟踪 DOM 操作以查找元素的可见性?

node.js - Alexa 技能 : is it possible to pause and resume the skill programmatically?

javascript - 并且不与 Loopback 中的其他查询字段一起使用

javascript - 使用命令行 Babel 的 Typescript sourcemaps