87

I got an error when using this line of code

const sass = require('gulp-sass')(require('sass'));

The error output is :

Requiring external module babel-register
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 'C:\xampp-clean\htdocs\myfirsttheme\package.json' contains "type": "module". T
o treat it as a CommonJS script, rename it to use the '.cjs' file extension.

I have changed

const sass = require('gulp-sass')(require('sass'));

the error disappeared but I am getting this error :

Requiring external module babel-register
TypeError: Cannot read property 'prod' of undefined

and this line is causing the error :

const PRODUCTION = yargs.argv.prod;

Do anyone has an idea?

I have tried a lot and googled this error but I did not find a solution , do anyone has an idea about this ? Thanks in advance

2
  • The problem shows up when using CommonJS syntax (require) in a ES module project: youtu.be/TXcFnsY5aqQ?t=237 Commented Feb 27, 2023 at 13:23
  • Also make sure you don't have import / export in that file, it should be module.exports instead of just export const or something Commented May 27 at 8:27

10 Answers 10

61

work for me , only change in package.json file, this line:

"type":"module" to "type":"commonjs"

Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me in a Playwright project.
61

While many node libraries support both require and import, I do occasionally run into cases where one library I need to use doesn't support require and another doesn't support import.

You can use createRequire to define require within an ES6 module and use that to also import Common JS libraries. Following is a sample code how to use it.

import { createRequire } from "module";
const require = createRequire(import.meta.url);

import crypto from 'crypto'
const fs = require('fs')

This answer is lifted straight from the this page: https://dev.to/caspergeek/how-to-use-require-in-ecmascript-modules-1l42

3 Comments

I get "Module not found: Error: Can't resolve 'module'"
This worked for me with dotenv const require = createRequire(import.meta.url); and then require("dotenv").config(); and I didn't have to change the type from module to commonjs
in got an same isssue but i fix the i am using cloudfunctions in cloudfucntions i am using UniqueId fucntions that is existing in frontend code but due to this create in cloud functions folder name utils and add // utils/uniqueID.js function uniqueID() { function chr4() { return Math.random().toString(16).slice(-4); } return ( chr4() + chr4() + "-" + chr4() + "-" + chr4() + "-" + chr4() + "-" + chr4() + chr4() + chr4() ); } module.exports = { uniqueID }; const { uniqueID } = require("./utils/index"); us
19

Can you check the "type" part in the package.json file? If the type part is module, you will get this error. You have to make it Commonjs.

6 Comments

{ "name": "myfirsttheme", "version": "1.0.0", "description": "description", "main": "index.js", "type": "module",
you mean "type":"commonjs"?
@askcoder If you're using require, the type should be commonjs.
Please add further details to expand on your answer, such as working code or documentation citations.
Using type "commonjs" in my package.json do the trick for me ! Thanks
|
10

This error is occurring because you are using "require" in a module.js environment.

This can occur either because you are in a file ending with .mjs OR You have defined your package.json to use the module type. E.g: "type": "module".

To fix this:

Change your requires to imports

const myModule = require("someModule") // ❌ using require inside of module scope
import myModule from "someModule" // ✅

Change your module.exports to exports

module.exports = (...) // ❌ using module inside of module scope
export default (...) // ✅

Alternatively:

If you need to use require (I recommend just changing require/module.exports to import and export), simply change your file extension from .js or .mjs to .cjs. This indicates to compilers that you want the type of this file to use features such as module and require.

Comments

3

Not directly applicable to OP but for those who spent a lot of time searching for a solution and finding that setting or removing "type" from package.json wasn't working, here it what fixed this issue for me.

  1. I tested out require by itself by executing the following in a separate file:
require('dotenv').config();

console.log(process.env);
  1. Upon seeing no errors and all my environment variables print out, I realized there must be something in my original server.js that must be causing the issue. I commented out the entire file except for the require('dotenv').config(); line, running the file and uncommenting subsequent lines until server.js broke. I discovered that uncommenting the following code causes the error:
    try {
        const testConnection = await pool.connect()
            .then(() => {
                console.log('Connected to PostgreSQL database');
            })
            .catch(err => {
                console.error('Connection error', err.stack);
            });
        testConnection.release();
    } catch (err) {
        console.error('Connection Error', err.stack);
    }

The issue at hand was that for some reason you can't use await at the top level of your code. await must be inside an async function. Since the above code literally just tests the connection to the db and then immediately disconnects, I just wrapped it as follows (and everything is back to normal!):

(async () => {
    try {
        ...
    } catch (err) {
        ...
    }
})();

Comments

1

If you are using Typescript and Jest and running into this problem, the answer provided by @prototype will get you halfway there, but you'll then run into an issue where Jest doesn't allow you to use import.meta.

Having now spent an enormous amount of time trying to get both import and require to work in both production and testing, I have arrived at a solution that I want to make sure I share:

Wherever you want to import a legacy package, you need the following:

function legacyRequireImport(path){
    if (process.env.NODE_ENV === "test"){
        return require(path);
    }
    const _require = createRequire(import.meta.url);
    return _require(path);
}
const someModule = legacyRequireImport("some_module");

Note: the function must be defined in the same file as it is being used. If you export this function and import it whenever you need it, it won't work. The function also cannot be called require, because that is a reserved word in commonJS (what Jest uses).

Now, if you just run that then you will get the following Jest error:

- error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.
     const _require = createRequire(import.meta.url);

In order to fix that, you can install a package called ts-jest-mock-import-meta and add the following to your jest.config:

    "transform": {
        "^.+\\.(j|t)s?$": ["ts-jest",
            {
                useESM: false,
                diagnostics: {
                    ignoreCodes: [1343]
                },
                astTransformers: {
                    before: [ "node_modules/ts-jest-mock-import-meta"]
                }
            }
        ],
    }

(this assumes you are using ts-jest, which you probably are if you are using typescript and jest)

You also need to make sure that you do not have a preset set in your jest.config, or else this won't work.

I know this seems insane, and it truly is insane, but this was genuinely the best solution I could find. And it does work. Best of luck.

Comments

0

A very different way to look at this issue, and I was having issues because of that. I tried a lot of different things and combinations, but the problem was because of Node Engines mismatch.
I was using node 24 but the engine mentioned in package.json was 20 as given below.
But I was getting the same error of import & required, and nowhere I didn't see anywhere the engine mismatched.

"engines": {
    "node": "20"
  }

To use a different Node Version you need NVM or Node Version Manager.
I'm providing commands for Mac, you can easily fine for windows.

# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
# Load nvm into your shell session (add these to ~/.zshrc if not auto-added)
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
# Restart your terminal, then:
nvm install 20 #you can set what every version you want to use.
nvm use 20

Comments

-2

This error occurs because require is a CommonJS module syntax, whereas import is an ES6 module syntax. to solve this, you should use import instead of require ; and in you json package the type must contain "type": "module" if you are using Node js

1 Comment

This answer could be improved by adding a code example.
-2

I attach a code fragment that compiles without errors

import { DynamoDBClient } from  '@aws-sdk/client-dynamodb';
import { S3Client } from  '@aws-sdk/client-s3';

export const handler = async (event) => {
  // TODO implement  
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  return response;
};

1 Comment

That code has nothing to do with Gulp or Sass. How is that code at all related to the question?
-7
  1. First of all add "type":"commonjs" to package.json.
  2. Downgrade your package version. If you are using gulp-imagemin version 8.0.0 then install older version like npm i [email protected].
    That's all now enjoy coding...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.