Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import fs in TypeScript

I know this seems like a duplicate question but none of the answers I've found works:

In my .ts file:

import * as fs from 'fs'; // error: SyntaxError: Unexpected token *
// OR
import fs from 'fs'; // error:
// import fs from 'fs';
//        ^^
// SyntaxError: Unexpected identifier

// OR

import {fs} from 'fs'; // error: module '"fs"' has no exported member 'fs'.ts(2305)


const data: [string, number] = [['one', 1],['two',2]];
function modifyThis(data: any) {
    return  data.map((element: any) => {
        element[1] = 0;
        return element;
    });
}
fs.writeFileSync('./data.txt', modifyThis(data), 'utf8');

I do have "@types/node": "^12.0.0" in my package.json and I don't understand why it doesn't work.

I execute the file with ts-node, node and code runner extension but it still doesn't work. I installed ts-node globally.

Update:

Output of $ts-node:

$ ts-node modData.ts 
/.../modData.ts:1
import * as fs from 'fs';
       ^

SyntaxError: Unexpected token *
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Module.m._compile (....nvm/versions/node/v10.16.0/lib/node_modules/ts-node/src/index.ts:814:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Object.require.extensions.(anonymous function) [as .ts] (....nvm/versions/node/v10.16.0/lib/node_modules/ts-node/src/index.ts:817:12)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at main (....nvm/versions/node/v10.16.0/lib/node_modules/ts-node/src/bin.ts:226:14)
    at Object.<anonymous> (....nvm/versions/node/v10.16.0/lib/node_modules/ts-node/src/bin.ts:485:3)

Update: tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}
like image 538
Viet Avatar asked Feb 05 '20 21:02

Viet


People also ask

Can not find module fs?

To solve the "Cannot find module fs or its corresponding type declarations" error, install the types for node by running the command npm i -D @types/node . You can then import fs with the following line of code import * as fs from 'fs' .

Can I use fs in Javascript?

With Node. js, you can programmatically manipulate files with the built-in fs module. The name is short for “file system,” and the module contains all the functions you need to read, write, and delete files on the local machine.

How do I read a text file in TypeScript?

Use the readFileSync() method to read a file's contents in TypeScript, e.g. readFileSync(join(__dirname, 'example. txt'), 'utf-8') . The method takes the path and encoding as parameters and returns the contents of the specified file.

What is fs in Javascript?

The Node.js file system module allows you to work with the file system on your computer. To include the File System module, use the require() method: var fs = require('fs'); Common use for the File System module: Read files.

How do I use the fs module in typescript?

To use the fs module in TypeScript, we can import the module with import. import * as fs from "fs"; import * as path from "path"; fs.readFile ( path.join (__dirname, "./client/index.html"), "utf8", (error, data) => { // ... } ); Then we call fs.readFile with the path of the file we want to read.

How do I export a function from a typescript module?

Use import * as chalk from "chalk";. A TypeScript module can say export default myFunction to export just one thing. Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object.

What is the difference between typescript and typescript module?

TypeScript also shares the same concept of a module. Any file which contains a top-level import or export is considered a module. The module is designed to arrange a code written in TypeScript and used as a local scope. Modules are basically scripts written in separate files. Import allows you to reference their source location in an existing file.

How to fix cannot find module FS or its type declarations?

To solve the "Cannot find module fs or its corresponding type declarations" error, install the types for node by running the command npm i -D @types/node. You can then import fs with the following line of code import * as fs from 'fs'.


2 Answers

import * as fs from 'fs';

I used the statement in my project, and it was fine.

Maybe check for tsconfig.json file?

"compilerOptions": {
     "module": "commonjs",
     ...
     /* List of folders to include type definitions from. */
    "types": [
        "node",
        "vue-types",
    ], 
 },
like image 160
HKK Avatar answered Oct 07 '22 19:10

HKK


I've figured out the issue: I need to install @types/node package outside of the react app with:

$ yarn add @types/node

So the project looks like this:

.
├── client
│   └── package.json
└── package.json
like image 45
Viet Avatar answered Oct 07 '22 20:10

Viet