網站搜尋

node.js - 在 TypeScript 中匯入 fs


我知道這似乎是重複的問題,但我找到的答案都沒有用:

在我的 .ts 檔案中:

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');

我確實在我的 package.json 中有 "@types/node": "^12.0.0",但我不明白為什麼它不起作用。

我使用 ts-node、node 和 Code Runner 擴展執行該檔案,但它仍然無法運行。我已經全域安裝了 ts-node。

更新:

$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)

更新: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"
  ]
}

答案#1

import * as fs from 'fs';

我在我的專案中使用了這個陳述,結果很好。

也許檢查一下 tsconfig.json 檔案?

"compilerOptions": {
     "module": "commonjs",
     ...
     /* List of folders to include type definitions from. */
    "types": [
        "node",
        "vue-types",
    ], 
 },

答案#2

我已經找出問題了:我需要在 react 應用程式之外安裝 @types/node 套件,方法如下:

yarn add @types/node

所以這個專案看起來是這樣的:

.
├── client
│   └── package.json
└── package.json