typescripteslinttypescript-eslint

Getting a linting error of no-var-requires


I am getting the error below on running the eslint.

\helpers\getEnvCredentials.ts 4:9 error Require statement not part of import statement @typescript-eslint/no-var-requires

✖ 1 problem (1 error, 0 warnings)

That error is referring to these lines of code wherein it is saying that using the "require" statement should be use only on imports. Please see (https://typescript-eslint.io/rules/no-var-requires/) for reference

const dataCredentials = JSON.parse(
JSON.stringify(
    require("../fixtures/credentials/" + env + "-credentials.json")
    )
);

Is there another way to do that line of codes above that will be accepted by eslint?


Solution

  • Depending on eslint & node version, there are three available options.

    Option #1. Disable the rule via inline comment

    This one is the easiest:

    const dataCredentials = JSON.parse(
    JSON.stringify(
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        require("../fixtures/credentials/" + env + "-credentials.json")
        )
    );
    

    Option #2. Use FileSystem module to read JSON files

    import fs from "node:fs";
    
    // I don't know whether `fs` will resolve the relative path correctly,
    // so better use absolute path.
    const dataCredentialsLocation = new URL(
      `../fixtures/credentials/${env}-credentials.json`, import.meta.url,
    );
    
    // readFileSync returns a buffer that has to be converted into a string.
    const dataCredentialsString = fs.readFileSync(dataCredentialsLocation).toString();
    
    // The string can be parsed into an object.
    const dataCredentials = JSON.parse(dataCredentialsString);
    

    Option #3. Split ESLint config

    If you're using "flat" ESLint config, you can specify what rules should be disabled for NodeJS modules.