Scenario
We currently require fs
like this in node:
const fs = require('fs');
but When we try to import libraries in a .ts file, VS Code marks the corresponding line with an error:[ts] Cannot find module 'fs'
. This happens no matter how I try to import the library:
import * as fs from 'fs'; // [ts] Cannot find module 'fs'
import fs = require('fs'); // [ts] Cannot find module 'fs'
const fs = require('fs'); // [ts] Cannot find name 'require'
We are wondering what the equivalent typescript version is?
Answer
With Typescript, after running npm install --save-dev @types/node
we can import the fs
the specific function we want from the fs
library with a destructured import like this:
import * as fs from 'fs';
// or if we just want to use one specific function of the fs module like WriteFileSync for //example
import { writeFileSync } from ‘fs';
The destructured part is important in the event that you want to minimize the module you are writing with tools like Webpack / Rollup. Since we are now only importing what we need, the remaining parts of the library we are importing from can be shaved off.