Skip to content

Maybe copy new ERR_REQUIRE_ESM error messaging from node #1407

Activity

  1. cspotcode commented on Jul 22, 2021

    @cspotcode
    CollaboratorAuthor

    filename, hasEsmSyntax, parentPath = null, packageJsonPath = null

    require() of ES Module ${filename}${parentPath ? ` from ${
          parentPath}` : ''} not supported.
    
        if (!packageJsonPath) {
          if (StringPrototypeEndsWith(filename, '.mjs'))
            msg += `\nInstead change the require of ${filename} to a dynamic ` +
                'import() which is available in all CommonJS modules.';
          return msg;
        }
        const path = require('path');
        const basename = path.basename(filename) === path.basename(parentPath) ?
          filename : path.basename(filename);
        if (hasEsmSyntax) {
          msg += `\nInstead change the require of ${basename} in ${parentPath} to` +
            ' a dynamic import() which is available in all CommonJS modules.';
          return msg;
        }
    
    ${basename} is treated as an ES module file as it is a .js 
    file whose nearest parent package.json contains "type": "module" 
    which declares all .js files in that package scope as ES modules.
    
    Instead rename ${basename} to end in .cjs, change the requiring 
    code to use dynamic import() which is available in all CommonJS 
    modules, or change "type": "module" to "type": "commonjs" in 
    ${packageJsonPath} to treat all .js files as CommonJS (using .mjs for 
    all ES modules instead).
    

    We can detect when it's .ts or .tsx and adapt the message to explain how our rules work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions