カテゴリー
未分類

TypeScript Error TS2307: Cannot find module ‘fs’. was resolved by installing the @types/node package. [2020]

Node.js has many useful built-in modules.

The fs module to handle the file system is one of them.

In TypeScript, it seems that @types/node is needed to use these modules provided by Node.js.

To add the @types/node package, run the following command.

npm install --save-dev @types/node

More details

I tried to write a little useful program in TypeScript, so I created a tool folder by executing the following commands in sequence.

I installed the TypeScript module and created an empty index.ts file.

mkdir tool
cd tool
npm init -y 
npm install typescript
touch index.ts

Since the index.ts file is empty to begin with, I used a text editor to write the following and saved it.

import * as fs from 'fs';
fs.writeFileSync('a.txt', 'b')

Then I ll compile it with the following command.

npx tsc index.ts 

At this stage, an error has occurred.

The errors that occurred are as follows.

index.ts:1:21 - error TS2307: Cannot find module 'fs'.


1 import * as fs from 'fs';
                      ~~~~




Found 1 error.

It should have created the index.js file automatically, but due to this error, it was not created.

The error message says that the fs module is not found.

The fs module is already bundled with Node.js.
If I wrote the code in JavaScript, I did not need to do any special preparation to use it.

However, in order to write code in TypeScript, a suitable type definition file seems to be needed.

So, run the following command as described above.

npm install --save-dev @types/node

Then we’ll try compiling again.

npx tsc index.ts 

Then the index.js file will be created successfully.

Let’s run the index.js file by the node command.

node index.js

Then an a.txt file will be created, and if the string “b” is written in it, it is as intended.

So TypeScript might not know what Node.js standard library has. And it seems to me that it’s the @types/node package that tells you that.