Require语句不是import语句的一部分eslint @ typescript-eslint / no-var-需要从存储中导入打字稿

问题描述

我必须从Firebase存储桶中导入一个打字稿文件。它包含数据以及类型定义。

export interface MyData {
 // ...
}

export const myData = {
 // ...
}

这是我随附的代码

export const readData = async (fileDir: string,fileName: string): Promise<object> => {
  // Open the bucket
  const bucket: Bucket = admin.storage().bucket()
  // Define the file path in the bucket
  const filePath: string = path.join(fileDir,fileName)
  // Define the local file path on the cloud function's server
  const tempFilePath: string = path.join(os.tmpdir(),fileName)
  // Download the file from the bucket
  try {
    await bucket.file(filePath).download({ destination: tempFilePath })
  } catch (error) {
    functions.logger.error(error,{ structuredData: true })
  }
  // Extract the needed variable export from the file
  const data = require(tempFilePath)
  // provide the variable
  return data
}

eslint抱怨:

Require语句不属于import语句。eslint@ typescript-eslint / no-var-requires

开启:

const data = require(tempFilePath)

什么是导入文件的正确方法

谢谢

解决方法

eslint错误消息包含错误代码“ typescript-eslint / no-var-requires”。在网络上搜索该字符串的过程是documentation

除在import语句中之外,禁止使用require语句 (no-var-requires)

换句话说,使用var foo = require("foo")之类的形式是 被禁止。而是使用ES6样式导入或import foo = require("foo") 进口。

您将必须放松您的陪同规则以避免此消息(不建议),或者接受其建议并更改代码的语法以使用import

如果您使用的是TypeScript,则应阅读import()函数提供的dynamic imports的文档。