ReferenceError: require is not defined in ES module scope, you can use import instead gulp sass
Asked Answered
T

7

62

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

Thunderous answered 8/9, 2021 at 8:41 Comment(1)
The problem shows up when using CommonJS syntax (require) in a ES module project: youtu.be/TXcFnsY5aqQ?t=237Bermejo
F
39

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

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

Famagusta answered 2/12, 2022 at 19:15 Comment(0)
S
28

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

Surgy answered 5/9, 2023 at 19:7 Comment(1)
I get "Module not found: Error: Can't resolve 'module'"Television
B
18

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.

Battleax answered 8/9, 2021 at 8:46 Comment(6)
{ "name": "myfirsttheme", "version": "1.0.0", "description": "description", "main": "index.js", "type": "module",Thunderous
you mean "type":"commonjs"?Thunderous
@Thunderous If you're using require, the type should be commonjs.Battleax
Please add further details to expand on your answer, such as working code or documentation citations.Judaic
I have updated the question with new detailsThunderous
Using type "commonjs" in my package.json do the trick for me ! ThanksOttinger
B
3

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.

Blues answered 3/6 at 4:49 Comment(0)
D
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.

Dolhenty answered 6/3 at 2:10 Comment(0)
A
-3

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

Andrel answered 30/4, 2023 at 10:17 Comment(1)
This answer could be improved by adding a code example.Histrionic
C
-6
  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...
Cletis answered 18/11, 2021 at 16:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.