1

I have to import a typescript file from the Firebase storage bucket. It contains data as well as type definitions.

export interface MyData {
 // ...
}

export const myData = {
 // ...
}

Here is the code I came with:

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 complain about:

Require statement not part of import statement.eslint@typescript-eslint/no-var-requires

On:

const data = require(tempFilePath)

What would be the right way to import the file?

Thanks

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Xiiryo
  • 3,021
  • 5
  • 31
  • 48

1 Answers1

6

The eslint error message contains the error code "typescript-eslint/no-var-requires". Doing a web search for that string comes up with the documentation:

Disallows the use of require statements except in import statements (no-var-requires)

In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.

You will have to either relax your eslint rules to avoid this message (not recommended), or accept its suggestion and change the syntax of your code to use import.

If you're using TypeScript, you should read the documentation for dynamic imports available with the import() function.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thanks, const data = await import(tempFilePath) works nicely. – Xiiryo Sep 22 '20 at 19:43
  • Similar issue that I was facing: https://stackoverflow.com/questions/66179935/how-to-resolve-typescript-eslint-no-var-requires-error-error-while-adding-axe (Includes solution) – Neil Feb 14 '21 at 19:07