How to find module "fs" in VS Code with TypeScript?

我在 MacBook Air 上运行。我安装了 VS Code 作为 IDE,也安装了 TypeScript。

I have a simple file with just this line:

import fs = require('fs');

我在括号内的“ fs”下面看到一个红色的波浪形,错误消息是 [ts] Cannot find module 'fs'.。它的延伸。我对 JavaScript 和 TypeScript 都是新手,但我的印象是 fs是一个核心模块,那么怎么可能找不到它呢?我如何解决这个问题?

Other things that I tried already:

  • 在文件中放入一个简单的函数体,然后使用 tsc在命令行上进行编译。我得到了一个本质上相等的错误: error TS2307: Cannot find module 'fs'.
  • 在命令行 sudo npm install fs -g上。这报告了明显的成功,但是没有解决问题。

我浏览了 SE 和网站,但是看起来很接近的答案似乎都假设“ fs”是可用的。

116270 次浏览

"fs" is a core Node module and I think your import statement syntax is a little off. Try:

import * as fs from "fs";

您需要包含节点的定义文件。

TypeScript 2.0 +

使用 npm 安装:

npm install --save-dev @types/node

TypeScript < 2.0

If you use 打字 then you can run this command:

typings install dt~node --global --save

或者如果使用的是 < 1.0类型,则运行:

typings install node --ambient --save

或者,如果所有其他方法都失败,则手动下载文件 给你并将其包含在项目中。

类型脚本知道基于约定的模块,查看 模组分辨率了解更多细节。

为了让 IDE 了解 fs模块,还必须提供节点的类型。

再看看这个 Github 的问题

现在有一个更好的方法,不需要使用以前的 tsd 或者类型工具。 NPM 现在有了用于类型脚本的@type 包:

npm install "@types/node" --save-dev

确保使用 save-dev 选项仅在开发模式下安装类型,而不是在生产模式下安装类型。在使用 npm install“@types/”语法时,应该有最新的节点库..。

它没有找到 fs 包,因为以前的工具很可能没有使用最新的 node.d.ts 定义文件。

需要更新 tsconfig.json 文件以查找这些类型包。 我的示例如果使用 jquery、 jqueryui 和节点类型。假设您的代码编辑器也需要这种语法,在本例中是“ atom”代码编辑器

{
"compileOnSave": false,
"compilerOptions": {
"rootDir": "src",
"sourceMap": true,
"target": "es5",
"module": "amd",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"lib": ["es2015", "dom"],
"baseUrl": "./",
"typeRoots": [
"node_modules/@types"
],
"types": [
"jquery",
"jqueryui",
"node"
],
"paths": {
"src/*": ["src/*"]
}
},
"exclude": [
"node_modules",
"dist",
"build"
],
"filesGlob": [
"./src/**/*.ts",
"./test/**/*.ts",
"./typings/index.d.ts",
"./custom_typings/**/*.d.ts",
"./node_modules/@types/**/*.d.ts"
],
"atom": {
"rewriteTsconfig": false
}
}

您所需要的只是在 tsconfig.json 中将“ moduleResolution”设置为“ node”:

{
"compilerOptions": {
...
"moduleResolution": "node"
...
}
}

执行

npm install @types/node --save-dev

and now you can use standard TypeScript import:

import * as fs from "fs";

tsconfig.json中有三个选项(这里是节点11 +) ,请参阅 医生:

无论是 具体点typeRootstypes,只有 typeRoots拿开两条线完全(推荐) :

{"compilerOptions": {
...
"typeRoots": ["node_modules/@types"],  // "typeRoots": [] -> won't work
"types": ["node"]                      // "types": [] -> won't work
}}

安装类型:

npm install --save-dev @types/node

使用基于承诺的文件系统(例如使用异步/等待) :

import {promises as fs} from 'fs';


async function foo() {
...
await fs.writeFile('./yourPath', 'YourContent');
}

on my side this work

 const fs = require('fs') as typeof import('fs');

对于新加坡电视台来说

 const fs = nw.require('fs') as typeof import('fs');

这样就去掉了 any