繁体   English   中英

未捕获的类型错误:fs_1.default.readFileSync 不是 function

[英]Uncaught TypeError: fs_1.default.readFileSync is not a function

我在一个项目中使用 Parcel 捆绑器,但我最大的障碍之一是我正在使用 Node 标准库中的fs模块,结果出现此错误:

fs_1.default.readFileSync is not a function

上面的错误是基于这个逻辑:

import fs from 'fs';

class Data {
  Address: string;
  General_Plan_Designation: string;
  Latitude: number;
  Longitude: number;

  static DELIMITER = ",";

  constructor(rawRow) {
    const data = rawRow.split(Data.DELIMITER);

    this.Address = data[0];
    this.General_Plan_Designation = data[1];
    this.Latitude = parseFloat(data[2]);
    this.Longitude = parseFloat(data[3]);
  }
}

const ROW_DELIMITER = "\r\n";

const rawData = fs.readFileSync("Cales_trim_down.csv", {
  encoding: "utf-8",
});

const data: Data[] = [];

for (const rawRow of rawData.split(ROW_DELIMITER)) {
  data.push(new Data(rawRow));
}

console.log(data);

我被告知要import * as whateverFS from 'fs'; 但这并没有解决问题。 有人告诉我将 go 放入tsconfig.json文件中,并确保将 esModule 设置为true ,但 Parcel 没有,至少没有一个我可以重新配置。

如何让 Node 标准库模块与 Parcel 一起使用?

因此,当将 TypeScript 与 Node 标准库模块一起使用并使用 Parcel 运行本地服务器时,您不能像我之前那样在全局安装 Parcel 并像parcel index.html一样运行它。

在这种情况下,您必须创建一个package.json文件:

{
  "scripts": {
    "build": "parcel build ./src/index.ts --target node",
    "start": "parcel index.html"
  },
  "devDependencies": {
    "typescript": "^4.2.4"
  },
  "dependencies": {
    "@types/googlemaps": "^3.43.3",
    "@types/node": "^15.0.2",
    "fs": "0.0.1-security",
    "parcel-bundler": "^1.12.5",
    "path": "^0.12.7"
  }
}

这是解决方案的 A 部分,B 部分不是使用fs.readFileSync()你必须像这样导入readFileSync()

import { readFileSync } from "fs";

并像这样应用它:

export const rawData = readFileSync("src/Cales_trim_down.csv", {
  encoding: "utf-8",
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM