skip to Main Content

EDIT: Minimal Reproducible Code attached below

I am able to successfully build an old codebase of ours but when running the code using node ui/dist/server, I am getting an error:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/user/code/node/myapp/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at Object.@babel/runtime/helpers/interopRequireDefault (file:///Users/user/code/node/myapp/ui/dist/server/index.js:19088:1)
    at __webpack_require__ (file:///Users/user/code/node/myapp/ui/dist/server/index.js:20072:40)
    at file:///Users/user/code/node/myapp/ui/dist/server/index.js:20119:30
    at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
    at ModuleLoader.import (node:internal/modules/esm/loader:473:24)
    at asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)

My babelrc is:

{
  "presets": [
    [
      "@babel/preset-env", {
        "targets": {
          "esmodules": true
        },
        "modules": false
      }
    ],
    ["@babel/preset-react", {
      "runtime": "automatic" 
    }]
  ],
  "sourceType": "unambiguous",
  "plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-transform-modules-commonjs",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-transform-destructuring",
    "@babel/plugin-transform-parameters",
    "transform-decorators-legacy",
    "@babel/plugin-transform-class-properties",
    "syntax-dynamic-import"
  ],
  "env": {
    "development": {
      "plugins": [
        "transform-react-jsx-self"
      ]
    },
    "production": {
      "presets": [
        "react-optimize"
      ]
    },
    "test": {
      "plugins": [
        // "transform-es2015-modules-commonjs", 
        "dynamic-import-node"
      ]
    }
  }
}

I tried experimenting with the @babel/plugin-transform-modules-commonjs plugin but the error persists. The error is in a build file.

Line 20119:

var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "@babel/runtime/helpers/interopRequireDefault");

Line 19088:

module.exports = require("@babel/runtime/helpers/interopRequireDefault");

Package.json snippets:

"type: module"

"dependencies": {

"@babel/plugin-transform-react-jsx": "^7.25.2",
"@babel/runtime": "^7.25.0",
"babel-plugin-transform-react-jsx-self": "^6.22.0",
}

Minimal Reproducible Code:
https://github.com/Exter-dg/minimalBabel

Edit:
I created a minimal reproducible example where I just print today’s date (in server.js) using moment. I have used same babel config and webpack config. The dist/server/index.js file that babel-node generates is using import statements from my coedebase as expected.
However, it also uses __webpack_modules__ which uses require to import dependencies. This is causing the error. Seems like a configuration mistake in babel/Webpack

2

Answers


  1. The issue is from the fact that your codebase is being treated as an ES module (due to the "type": "module" field in package.json), but Webpack is generating CommonJS-style require calls, which are incompatible with ES module syntax.

    Your Webpack is generating require calls, you need to make sure that your configuration properly handles ES modules. You can fix it like so:

    // webpack.config.js
    module.exports = {
      output: {
        filename: 'bundle.js',
        libraryTarget: 'module',  // Use ES Module
      },
      experiments: {
        outputModule: true,  // This allows Webpack to output ESM
      },
      // Ensure target is modern
      target: ['web', 'es2020'], 
    };
    
    Login or Signup to reply.
  2. The error you’re encountering is due to the conflict between ES module syntax (using import) and CommonJS syntax (using require). Since your project is set up to treat JavaScript files as ES modules ("type": "module" in package.json), but some parts of the generated code are still trying to use require, you need to ensure that the entire build process is consistent.

    Either you can use latest ES module or CommonJs. Here you have tried to use both with @babel/plugin-transform-modules-commonjs.

    Here are some steps to help you resolve the issue:

    1. Update Babel Configuration:

    Make sure your Babel configuration is set up to transpile your code correctly for ES modules. You can try removing the @babel/plugin-transform-modules-commonjs plugin, as it converts ES module syntax to CommonJS, which is not needed if you’re targeting ES modules.

    2. Webpack Configuration:

    Ensure that your Webpack configuration is set up to handle ES modules correctly. If you’re using Webpack 5, it should support ES modules out of the box. Check that you’re using the right loaders and configurations. Make sure you’re not trying to mix require and import in your entry files.

    3. Check the Entry Point:

    Ensure that your entry point (server.js or equivalent) uses import statements instead of require. If you’re using import, make sure all your dependencies also support ES module syntax.

    4. Dist File Naming:

    If you continue to face issues, consider renaming the output files in the dist directory to have a .mjs extension, which can help Node.js recognize them as ES modules.

    5. Running the Application
    When you run your application, try to use the following command to ensure Node.js treats your files correctly:

    node --experimental-specifier-resolution=node ui/dist/server/index.js

    If still issue persist please check your directory files and ensure that everywhere you have used import or not. is there any place where you have used require or not. Please check. May be this can help you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search