Parsing error must use import to load es module

I am currently setting up a boilerplate with React, TypeScript, styled components, Webpack, etc., and I am getting an error when trying to run ESLint: Error: Must use import to load ES Module Her...

I am currently setting up a boilerplate with React, TypeScript, styled components, Webpack, etc., and I am getting an error when trying to run ESLint:

Error: Must use import to load ES Module

Here is a more verbose version of the error:

/Users/ben/Desktop/development projects/react-boilerplate-styled-context/src/api/api.ts
  0:0  error  Parsing error: Must use import to load ES Module: /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/lib/definition.js
require() of ES modules is not supported.
require() of /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/lib/definition.js from /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/babel-eslint/lib/require-from-eslint.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename definition.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/package.json

The error occurs in every single one of my .js and .ts/ .tsx files where I only use import or the file doesn’t even have an import at all. I understand what the error is saying, but I don’t have any idea why it is being thrown when in fact I only use imports or even no imports at all in some files.

Here is my package.json file where I trigger the linter from using npm run lint:eslint:quiet:

{
  "name": "my-react-boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.tsx",
  "directories": {
    "test": "test"
  },
  "engines": {
    "node": ">=14.0.0"
  },
  "type": "module",
  "scripts": {
    "build": "webpack --config webpack.prod.js",
    "dev": "webpack serve --config webpack.dev.js",
    "lint": "npm run typecheck && npm run lint:css && npm run lint:eslint:quiet",
    "lint:css": "stylelint './src/**/*.{js,ts,tsx}'",
    "lint:eslint:quiet": "eslint --ext .ts,.tsx,.js,.jsx  ./src --no-error-on-unmatched-pattern --quiet",
    "lint:eslint": "eslint --ext .ts,.tsx,.js,.jsx  ./src --no-error-on-unmatched-pattern",
    "lint:eslint:fix": "eslint --ext .ts,.tsx,.js,.jsx  ./src --no-error-on-unmatched-pattern --quiet --fix",
    "test": "cross-env NODE_ENV=test jest --coverage",
    "test:watch": "cross-env NODE_ENV=test jest --watchAll",
    "typecheck": "tsc --noEmit",
    "precommit": "npm run lint"
  },
  "lint-staged": {
    "*.{ts,tsx,js,jsx}": [
      "npm run lint:eslint:fix",
      "git add --force"
    ],
    "*.{md,json}": [
      "prettier --write",
      "git add --force"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "npx lint-staged && npm run typecheck"
    }
  },
  "resolutions": {
    "styled-components": "^5"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.5.4",
    "@babel/plugin-proposal-class-properties": "^7.5.0",
    "@babel/preset-env": "^7.5.4",
    "@babel/preset-react": "^7.0.0",
    "@types/history": "^4.7.6",
    "@types/react": "^17.0.29",
    "@types/react-dom": "^17.0.9",
    "@types/react-router": "^5.1.17",
    "@types/react-router-dom": "^5.1.5",
    "@types/styled-components": "^5.1.15",
    "@typescript-eslint/eslint-plugin": "^5.0.0",
    "babel-cli": "^6.26.0",
    "babel-eslint": "^10.0.2",
    "babel-loader": "^8.0.0-beta.6",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "clean-webpack-plugin": "^4.0.0",
    "dotenv-webpack": "^7.0.3",
    "error-overlay-webpack-plugin": "^1.0.0",
    "eslint": "^8.0.0",
    "eslint-config-airbnb": "^18.2.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-config-with-prettier": "^6.0.0",
    "eslint-plugin-compat": "^3.3.0",
    "eslint-plugin-import": "^2.25.2",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.14.2",
    "eslint-plugin-react-hooks": "^4.2.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.3.2",
    "husky": "^7.0.2",
    "prettier": "^2.4.1",
    "raw-loader": "^4.0.2",
    "style-loader": "^3.3.0",
    "stylelint": "^13.13.1",
    "stylelint-config-recommended": "^5.0.0",
    "stylelint-config-styled-components": "^0.1.1",
    "stylelint-processor-styled-components": "^1.10.0",
    "ts-loader": "^9.2.6",
    "tslint": "^6.1.3",
    "typescript": "^4.4.4",
    "url-loader": "^4.1.1",
    "webpack": "^5.58.2",
    "webpack-cli": "^4.2.0",
    "webpack-dev-server": "^4.3.1",
    "webpack-merge": "^5.3.0"
  },
  "dependencies": {
    "history": "^4.10.0",
    "process": "^0.11.10",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "styled-components": "^5.2.1"
  }
}

Here is my .eslintrc file:

{
  "extends": ["airbnb", "prettier"],
  "parser": "babel-eslint",
  "plugins": ["prettier", "@typescript-eslint"],
  "parserOptions": {
    "ecmaVersion": 8,
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "impliedStrict": true,
      "classes": true
    }
  },
  "env": {
    "browser": true,
    "node": true,
    "jest": true
  },
  "rules": {
    "arrow-body-style": ["error", "as-needed"],
    "class-methods-use-this": 0,
    "react/jsx-filename-extension": 0,
    "global-require": 0,
    "react/destructuring-assignment": 0,
    "import/named": 2,
    "linebreak-style": 0,
    "import/no-dynamic-require": 0,
    "import/no-named-as-default": 0,
    "import/no-unresolved": 2,
    "import/prefer-default-export": 0,
    "semi": [2, "always"],
    "max-len": [
      "error",
      {
        "code": 80,
        "ignoreUrls": true,
        "ignoreComments": true,
        "ignoreStrings": true,
        "ignoreTemplateLiterals": true
      }
    ],
    "new-cap": [
      2,
      {
        "capIsNew": false,
        "newIsCap": true
      }
    ],
    "no-param-reassign": 0,
    "no-shadow": 0,
    "no-tabs": 2,
    "no-underscore-dangle": 0,
    "react/forbid-prop-types": [
      "error",
      {
        "forbid": ["any"]
      }
    ],
    "import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
    "react/jsx-no-bind": [
      "error",
      {
        "ignoreRefs": true,
        "allowArrowFunctions": true,
        "allowBind": false
      }
    ],
    "react/no-unknown-property": [
      2,
      {
        "ignore": ["itemscope", "itemtype", "itemprop"]
      }
    ]
  }
}

And I’m not sure if it is relevant, but here is also my tsconfig.eslint.json file:

{
  "extends": "./tsconfig.json",
  "include": ["./src/**/*.ts", "./src/**/*.tsx", "./src/**/*.js"],
  "exclude": ["node_modules/**", "build/**", "coverage/**"]
}

How can I fix this?

Googling the error does not present any useful forums or raised bugs. Most of them just state not to use require in your files which I am not.

Hello Guys, How are you all? Hope You all Are Fine. Today I face the following error Error [ERR_REQUIRE_ESM]: Must use import to load ES Module in nodejs. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

Contents

  1. How Error [ERR_REQUIRE_ESM]: Must use import to load ES Module Error Occurs ?
  2. How To Solve Error [ERR_REQUIRE_ESM]: Must use import to load ES Module Error ?
  3. Solution 1: Just Use latest version of node
  4. Solution 2: add «type»: «module» in your package.json
  5. Solution 3: Change node version
  6. Summery

I am trying to import userField from my users.js file into my index.js file But I am facing following error.

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

Here is my users.js

export let userField = ['username', 'email', 'dob', 'firstname', 'lastname'];

Here is my index.js

import { userField } from './users.js';
console.log(userField);

How To Solve Error [ERR_REQUIRE_ESM]: Must use import to load ES Module Error ?

  1. How To Solve Error [ERR_REQUIRE_ESM]: Must use import to load ES Module Error?

    To Solve Error [ERR_REQUIRE_ESM]: Must use import to load ES Module Error This code is perfect, But I recommend you should use the latest version of the node. I ran your code on my PC and working Fine. Just remember Node version >= 14. It only works with the latest version of the node.

  2. Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

    To Solve Error [ERR_REQUIRE_ESM]: Must use import to load ES Module Error This code is perfect, But I recommend you should use the latest version of the node. I ran your code on my PC and working Fine. Just remember Node version >= 14. It only works with the latest version of the node.

Solution 1: Just Use latest version of node

This code is perfect, But I recommend you should use the latest version of the node. I ran your code on my PC and working Fine. Just remember Node version >= 14. It only works with the latest version of the node.

Solution 2: add “type”: “module” in your package.json

Make sure your package.json includes a line for “type”: “module”, Without this line node assumes you want to use Common JS modules rather than ESM.

Solution 3: Change node version

  1. Change node version to the one required by this project and build again.
  2. Stay on the node version you have and remove node_modules directory and package-lock.json file and do npm install again.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also Read

  • SyntaxError: invalid syntax to repo init in the AOSP code.

Содержание

  1. [ERROR] Must use import to load ES module #314
  2. Comments
  3. Issue description
  4. Context
  5. ts-node-dev: ^2.0.0
  6. Error: «Must use import to load ES Module», but I’m already using import ! #9223
  7. Comments
  8. Versions
  9. Reproduction
  10. Steps to reproduce
  11. What is Expected?
  12. What is actually happening?
  13. Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: . #8900
  14. Comments
  15. Describe the bug
  16. Did you try recovering your dependencies?
  17. Which terms did you search for in User Guide?
  18. Environment
  19. Steps to reproduce
  20. Expected behavior
  21. Actual behavior
  22. Reproducible demo
  23. npx create-react-app fails Must use import to load ES Module #8897
  24. Comments
  25. Describe the bug
  26. Did you try recovering your dependencies?
  27. Which terms did you search for in User Guide?
  28. Environment
  29. Steps to reproduce
  30. Expected behavior
  31. Actual behavior
  32. Reproducible demo
  33. My SO: macOS Catalina 10.15.4
  34. Error [ERR_REQUIRE_ESM]: Must use import to load ES Module?

[ERROR] Must use import to load ES module #314

Issue description

Context

Totally new Node project with typescript , @types/node , and ts-node-dev packages installed.
I only get this error when I set type: «module» in package.json .

ts-node-dev: ^2.0.0

OS version (is it docker or host?), ts-node-dev version

Did you try to run with ts-node?

Did you try to run with —files option enabled?

Did you try to run with —debug option enabled?

Do you have a repro example (git repo) with simple steps to reproduce your problem?

The text was updated successfully, but these errors were encountered:

I’m having the same problem

ts-node-dev version: 2.0.0
typescript version: 4.7.2

Switched to babel with @babel/preset-typescript, and nodemon. Everything is working there. Can use imports without filenames, can use directories with implied index.ts, and can use mongoose. Will try other packages later to confirm that everything works now.

Still having this issue with ts-node-dev. No matter what I try (type: «module» in package.json, module:»esnext» and module:»commonjs» in tsconfig.json, etc.)

Right now, my problem is with the package inquirer. It’s ready for ESM in new version v9.0.0. But if I remove type: «module» from package.json, inquirer complains. Then I replaced the import with a dynamic import await import(‘inquirer’), but then I get an error that can’t use top level await with a commonjs module.

But with babel and nodemon, and babel typescript presets it works flawlessly.

I’m reaching the conclusion that ts-node-dev isn’t ready for ESM so I will continue using babel and nodemon.

I have this exact same problem too, would it be possible to support this?

Same problem.
I’m using ts-node-dev while i’m developing. And there the error occures.
When i build my project for production with bable it’s woking.

Same problem. I’m using ts-node-dev while i’m developing. And there the error occures. When i build my project for production with bable it’s woking.
Yeah, with babel works.

You can try this config, I tested it with most ES2022 features (including Top Level Await) and it works.

Источник

Error: «Must use import to load ES Module», but I’m already using import ! #9223

Versions

Reproduction

Steps to reproduce

  1. Create a new Nuxt project.
  2. npm i hast-util-select to install the particular library I’m having trouble with (which by the way is part of a widely used ecosystem and work fine outside of Nuxt, so I’m pretty confident it’s not the problem here).
  3. Create a file

/plugins/test.js with the following code:

  1. Add the plugin to nuxt.config.js .

What is Expected?

The project runs without errors.

What is actually happening?

. is shown on the front-end.

The text was updated successfully, but these errors were encountered:

Does anyone have time to look into why this is happening?

Hey @AaronBeaudoin I ran into this today and was able to solve it by updating my nuxt.config.js build config to have it transpile the ESM packages like so:

Hey @AaronBeaudoin I ran into this today and was able to solve it by updating my nuxt.config.js build config.

This didn’t have any effect for me. If you open up the CodeSandbox above and try it there, you’ll see it makes no difference. Perhaps there’s something else in your setup which is resolving the issue?

@AaronBeaudoin I took a look and was able to get it working by adding all of the various esm packages to the transpile block of the nuxt config: take a look at my fork of your code sandbox

Initially I was adding them as dependencies but that might not be necessary.

I originally only transpiled the hast-util-select package itself and not its dependencies. Thanks for clarifying!

I wonder however, if this workaround should be necessary at all, but that might be another issue.

Adding esmodule dependencies (and their dependnecies) to build.transpile is a good idea.

Alternatively, you can use build.standalone: true in nuxt.config file. (see sandbox fork)

With either workaround, we avoid externalizing server bundle dependencies (nuxt2 uses CommonJS for building server and by default externalizes all node_modules . Which is why broken with new type of packages that are esm only.)

Since this kind of packages are getting more common in npm ecosystem, I think we might make a fork of webpack-node-externals that has continuous of package exports type, automatically inlining esmodules.

Источник

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: . #8900

Describe the bug

I’m trying to create a new React app using create-react-app and it in every way it just don’t work. it throws the following error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:UsersDevCarlosUDesktoptest-finalnode_modulesis-promiseindex.js

Did you try recovering your dependencies?

No, it’s for a new project.

Which terms did you search for in User Guide?

Environment

current version of create-react-app: 3.4.1
running from C:UsersDevCarlosUAppDataRoamingnpmnode_modulescreate-react-app

System:
OS: Windows 10 10.0.18362
CPU: (8) x64 Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz
Binaries:
Node: 12.16.2 — C:Program Filesnodejsnode.EXE
Yarn: Not Found
npm: 6.14.4 — C:Program Filesnodejsnpm.CMD
Browsers:
Edge: 44.18362.449.0
Internet Explorer: 11.0.18362.1
npmPackages:
react: Not Found
react-dom: Not Found
react-scripts: Not Found
npmGlobalPackages:
create-react-app: Not Found

Steps to reproduce

(Write your steps here:)

  1. cd Desktop
  2. npx create-react-app test
  3. error.

Expected behavior

A new and clean React App project

Actual behavior

PS C:UsersDevCarlosUDesktop> npx create-react-app test

Creating a new React app in C:UsersDevCarlosUDesktoptest.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template.

core-js@2.6.11 postinstall C:UsersDevCarlosUDesktoptestnode_modulesbabel-runtimenode_modulescore-js
node -e «trycatch(e)<>«

core-js@3.6.5 postinstall C:UsersDevCarlosUDesktoptestnode_modulescore-js
node -e «trycatch(e)<>«

core-js-pure@3.6.5 postinstall C:UsersDevCarlosUDesktoptestnode_modulescore-js-pure
node -e «trycatch(e)<>«

  • react-dom@16.13.1
  • cra-template@1.0.3
  • react@16.13.1
  • react-scripts@3.4.1
    added 1606 packages from 750 contributors and audited 931196 packages in 57.03s

58 packages are looking for funding
run npm fund for details

found 0 vulnerabilities

internal/modules/cjs/loader.js:1172
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:UsersDevCarlosUDesktoptestnode_modulesis-promiseindex.js
require() of ES modules is not supported.
require() of C:UsersDevCarlosUDesktoptestnode_modulesis-promiseindex.js from C:UsersDevCarlosUDesktoptestnode_modulesrun-asyncindex.js is an ES module file as it is a .js file whose nearest parent package.json contains «type»: «module» which defines all .js files in that package scope as ES modules.
Instead rename C:UsersDevCarlosUDesktoptestnode_modulesis-promiseindex.js to end in .cjs, change the requiring code to use import(), or remove «type»: «module» from C:UsersDevCarlosUDesktoptestnode_modulesis-promisepackage.json.

Aborting installation.
node has failed.

Deleting generated file. node_modules
Deleting generated file. package.json
Done.

Reproducible demo

(Paste the link to an example project and exact instructions to reproduce the issue.)

The text was updated successfully, but these errors were encountered:

Источник

npx create-react-app fails Must use import to load ES Module #8897

Describe the bug

npx create-react-app test —use-npm —template typescript failes with following error

If I try to install with yarn create react-app test —template typescript then I get following error

Did you try recovering your dependencies?

npm v 16.14.4
yarn v 1.22.4

Which terms did you search for in User Guide?

I searched exactly npx create-react-app not workin saw few old github issues.

Environment

Invalid «exports» main target «index.js» defined in the package config /home/apoorvmote/.config/yarn/global/node_modules/is-promise/package.json

Steps to reproduce

  1. brew install node@12
  2. npx create-react-app test —use-npm —template typescript
  3. yarn create react-app test —template typescript

Expected behavior

I literally created new react project today morning and deployed to production. I don’t know why suddenly its not working anymore.
It doesn’t work in Ubuntu 18.04 , Ubuntu 20.04 and Windows 10 Pro . Both Ubuntu running on WSL 2

Actual behavior

The error from windows 10 pro

Reproducible demo

(Paste the link to an example project and exact instructions to reproduce the issue.)

npx create-react-app test —use-npm —template typescript
yarn create react-app test —template typescript

The text was updated successfully, but these errors were encountered:

learning react for the first time today, im having the same issue

I have this problem too:
`➜ npx create-react-app my-app
npx: instaló 99 en 6.25s
Must use import to load ES Module: /Users/cristianandrescordovavalencia/.npm/_npx/4026/lib/node_modules/create-react-app/node_modules/is-promise/index.js
require() of ES modules is not supported.
require() of /Users/cristianandrescordovavalencia/.npm/_npx/4026/lib/node_modules/create-react-app/node_modules/is-promise/index.js from /Users/cristianandrescordovavalenci
a/.npm/_npx/4026/lib/node_modules/create-react-app/node_modules/run-async/index.js is an ES module file as it is a .js file whose nearest parent package.json contains «type
«: «module» which defines all .js files in that package scope as ES modules.
Instead rename /Users/cristianandrescordovavalencia/.npm/_npx/4026/lib/node_modules/create-react-app/node_modules/is-promise/index.js to end in .cjs, change the requiring c
ode to use import(), or remove «type»: «module» from /Users/cristianandrescordovavalencia/.npm/_npx/4026/lib/node_modules/create-react-app/node_modules/is-promise/package.j
son.

took 7s
➜ npx create-react-app test —use-npm
npx: instaló 99 en 3.81s
Must use import to load ES Module: /Users/cristianandrescordovavalencia/.npm/_npx/4064/lib/node_modules/create-react-app/node_modules/is-promise/index.js
require() of ES modules is not supported.
require() of /Users/cristianandrescordovavalencia/.npm/_npx/4064/lib/node_modules/create-react-app/node_modules/is-promise/index.js from /Users/cristianandrescordovavalenci
a/.npm/_npx/4064/lib/node_modules/create-react-app/node_modules/run-async/index.js is an ES module file as it is a .js file whose nearest parent package.json contains «type
«: «module» which defines all .js files in that package scope as ES modules.
Instead rename /Users/cristianandrescordovavalencia/.npm/_npx/4064/lib/node_modules/create-react-app/node_modules/is-promise/index.js to end in .cjs, change the requiring c
ode to use import(), or remove «type»: «module» from /Users/cristianandrescordovavalencia/.npm/_npx/4064/lib/node_modules/create-react-app/node_modules/is-promise/package.j
son.

My SO:
macOS Catalina 10.15.4

I try uninstall and install node and npm but it doesn’t work.

Источник

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module?

История
Делал настройку gulp по видео уроку. По началу все прекрасно работало, но как дошел до установки плагина «imagemin» возникли проблемы. Установил плагин при помощи кода npm install —save-dev gulp-imagemin

Компилятор

Я так понял там какие то проблемы с модулем. То есть, должен быть «ES module, а у меня используется «CommonJS» (что бы это ни значило). На форумах прочитал создать еще один «package.json» в папке «src», и прописать там <«type»: «module»>. Но это не помогло.

  • Вопрос задан более года назад
  • 11301 просмотр

Простой 1 комментарий

alexblackstone, а gulp-image так же ужимает размер файла ?
В плане задачи.

Поставил. Проверил. Работает.
Спасибо )

alexblackstone, Ух, эта сборка сделает седым.
При установке другого модуля «webpcss» далее.

Выдаёт новые приключения:

Error: Cannot find module ‘webp-converter/cwebp’
Require stack:
— G:DifferentWebAndrikanych Evhenfls-gulpnode_moduleswebpcssdistWebpBase64.js
— G:DifferentWebAndrikanych Evhenfls-gulpnode_moduleswebpcssdistWebpcss.js
— G:DifferentWebAndrikanych Evhenfls-gulpnode_moduleswebpcssdistindex.js
— G:DifferentWebAndrikanych Evhenfls-gulpnode_modulesgulp-webpcssindex.js
— G:DifferentWebAndrikanych Evhenfls-gulpgulpfile.js
— C:UsersCobraAppDataRoamingnpmnode_modulesgulp-clilibsharedrequire-or-import.js
— C:UsersCobraAppDataRoamingnpmnode_modulesgulp-clilibversioned^4.0.0index.js
— C:UsersCobraAppDataRoamingnpmnode_modulesgulp-cliindex.js
— C:UsersCobraAppDataRoamingnpmnode_modulesgulp-clibingulp.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:962:15)
at Function.Module._load (internal/modules/cjs/loader.js:838:27)
at Module.require (internal/modules/cjs/loader.js:1022:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object. (G:DifferentWebAndrikanych Evhenfls-gulpnode_moduleswebpcssdistWebpBase64.js:33:19)
at Module._compile (internal/modules/cjs/loader.js:1118:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1138:10)
at Module.load (internal/modules/cjs/loader.js:982:32)
at Function.Module._load (internal/modules/cjs/loader.js:875:14)
at Module.require (internal/modules/cjs/loader.js:1022:19) <
code: ‘MODULE_NOT_FOUND’,
requireStack: [
‘G:\Different\Web\Andrikanych Evhen\fls-gulp\node_modules\webpcss\dist\WebpBase64.js’,
‘G:\Different\Web\Andrikanych Evhen\fls-gulp\node_modules\webpcss\dist\Webpcss.js’,
‘G:\Different\Web\Andrikanych Evhen\fls-gulp\node_modules\webpcss\dist\index.js’,
‘G:\Different\Web\Andrikanych Evhen\fls-gulp\node_modules\gulp-webpcss\index.js’,
‘G:\Different\Web\Andrikanych Evhen\fls-gulp\gulpfile.js’,
‘C:\Users\Cobra\AppData\Roaming\npm\node_modules\gulp-cli\lib\shared\require-or-import.js’,
‘C:\Users\Cobra\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\index.js’,
‘C:\Users\Cobra\AppData\Roaming\npm\node_modules\gulp-cli\index.js’,
‘C:\Users\Cobra\AppData\Roaming\npm\node_modules\gulp-cli\bin\gulp.js’
]
>

Установил module ‘webp-converter’.
А вот как его применить не понимаю пока.

Источник

I am trying to fix this problem for hours. I’ve read nearly every post about this, but still, I came to no solution.

I am trying to deploy a firebase-function with the “https got-library” dependency, but no matter what I do, nothing works. I am not the best with node-js or typescript (usually a kotlin frontend-dev), so I have no clue what the error wants from me.

Tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": false,
    "esModuleInterop": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ],
}

.eslintrc.js

module.exports = {
  root: true,
  env: {
    es6: true,
    node: true,
  },
  extends: [
    "eslint:recommended",
    "plugin:import/errors",
    "plugin:import/warnings",
    "plugin:import/typescript",
    "google",
    "plugin:@typescript-eslint/recommended",
  ],
  parser: "@typescript-eslint/parser",
  parserOptions: {
    project: ["tsconfig.json", "tsconfig.dev.json"],
    sourceType: "module",
  },
  ignorePatterns: [
    "/lib/**/*", // Ignore built files.
  ],
  plugins: [
    "@typescript-eslint",
    "import",
  ],
  rules: {
    "quotes": ["error", "double"],
    "import/no-unresolved": 0,
    "linebreak-style": ["error", "windows"],
    "indent": "off",
    "object-curly-spacing": "off",
    "no-tabs": 0,
    "max-len": "off",
    "require-jsdoc": 0,
    "no-empty": [0, "allow-empty-functions", "allow-empty-catch"],
    "@typescript-eslint/no-explicit-any": ["off"],
    "@typescript-eslint/naming-convention": ["off"],
    "@typescript-eslint/explicit-function-return-type": "off",
    "@typescript-eslint/explicit-module-boundary-types": "off",
    "@typescript-eslint/no-var-requires": "off",
    "no-mixed-spaces-and-tabs": 0,
    "camelcase": 0,
  },
};

package.json

{
  "name": "functions",
  "scripts": {
    "lint": "eslint --ext .js,.ts .",
    "build": "tsc",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "14"
  },
  "type": "module",
  "main": "lib/index.js",
  "dependencies": {
    "@google-cloud/functions-framework": "^2.1.0",
    "@types/stripe": "^8.0.417",
    "firebase-admin": "^10.0.1",
    "firebase-functions": "^3.14.1",
    "firebase-tools": "^10.0.1",
    "form-data": "^4.0.0",
    "got": "^12.0.0",
    "iso3166-alpha-converter": "^1.0.0",
    "mailgun.js": "^4.1.0",
    "stripe": "^8.193.0"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.8.0",
    "@typescript-eslint/parser": "^5.8.0",
    "eslint": "^8.5.0",
    "eslint-config-google": "^0.14.0",
    "eslint-plugin-import": "^2.22.0",
    "firebase-functions-test": "^0.3.3",
    "typescript": "^4.5.4"
  },
  "private": true
}

Error

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:UsersImMorDocumentsFirebaseFunctionsfunctions.eslintrc.js
require() of ES modules is not supported.
require() of C:UsersImMorDocumentsFirebaseFunctionsfunctions.eslintrc.js from C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_modules@eslinteslintrcdisteslintrc.cjs is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename .eslintrc.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:UsersImMorDocumentsFirebaseFunctionsfunctionspackage.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at Object.module.exports [as default] (C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_modulesimport-freshindex.js:32:59)
    at loadJSConfigFile (C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_modules@eslinteslintrcdisteslintrc.cjs:2531:47)
    at loadConfigFile (C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_modules@eslinteslintrcdisteslintrc.cjs:2615:20)
    at ConfigArrayFactory.loadInDirectory (C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_modules@eslinteslintrcdisteslintrc.cjs:2808:34)
    at CascadingConfigArrayFactory._loadConfigInAncestors (C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_modules@eslinteslintrcdisteslintrc.cjs:3772:46)
    at CascadingConfigArrayFactory.getConfigArrayForFile (C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_modules@eslinteslintrcdisteslintrc.cjs:3693:18)

Function I want to deploy

// THIS IS MAKING THE PROBLEM
import got from "got";

export async function doOnDeletedUser(
    // SOME OTHER STUFF
) {
    const uid = user.uid;
    // SOME OTHER STUFF
}

Edit

Changing .eslintrc.js to .eslintrc.cjs solves this problem, but then I get the following error:

ReferenceError: exports is not defined
    at file:///C:/Users/ImMor/Documents/FirebaseFunctions/functions/lib/index.js:24:23
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:166:24)
    at async loadModule (C:UsersImMorAppDataRoamingnpmnode_modulesfirebase-toolslibdeployfunctionsruntimesnodetriggerParser.js:16:20)
    at async C:UsersImMorAppDataRoamingnpmnode_modulesfirebase-toolslibdeployfunctionsruntimesnodetriggerParser.js:34:15

Edit 2

Removing “type”:”module” then gives me this error again:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_moduleskydistributionindex.js
require() of ES modules is not supported.
require() of C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_moduleskydistributionindex.js from C:UsersImMorDocumentsFirebaseFunctionsfunctionslibauthonDeleteonDeletedUser.f.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:UsersImMorDocumentsFirebaseFunctionsfunctionsnode_moduleskypackage.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:UsersImMorDocumentsFirebaseFunctionsfunctionslibauthonDeleteonDeletedUser.f.js:27:30)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:UsersImMorDocumentsFirebaseFunctionsfunctionslibindex.js:39:27)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)

Edit 3

Following changes have been made:

  • Change “module” : “commonjs” -> “module”: “es6”
  • Change “target” : “es2017” -> “target”: “es6”
  • Add “moduleResolution”: “node” in tsconfig.js (inside compileroptions).
  • Add “type”:”module” to package.json

Now I am getting the following error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:UsersImMorDocumentsFirebaseFunctionsfunctionslibutilsconstants.f' imported from C:UsersImMorDocumentsFirebaseFunctionsfunctionslibindex.js
    at finalizeResolution (internal/modules/esm/resolve.js:276:11)
    at moduleResolve (internal/modules/esm/resolve.js:699:10)
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)
    at Loader.resolve (internal/modules/esm/loader.js:86:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:230:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:56:40)
    at link (internal/modules/esm/module_job.js:55:36)

Here is the code (constants.f.ts)

export const constants = {
/**
* Default firebase-functions region
*/
region: “europe-west1”,
} as const;

Edit 4

Looks like I’ve fixed all my problems. When using “module”: “es6”, one has to import its module like this:

import { constants } from "./utils/constants.js";

and not like this:

import { constants } from "./utils/constants";

The ending “.js” is important

Advertisement

Answer

Quoting from the ESLint documentation:

use .eslintrc.cjs when running ESLint in JavaScript packages that specify "type":"module" in their package.json. Note that ESLint does not support ESM configuration at this time.

Since you have "type": "module" in your package.json file you should be fine by renaming “.eslintrc.js” to “.eslintrc.cjs”.

4 People found this is helpful

Anton Golub

Anton Golub

Posted on Mar 31, 2021

• Updated on Nov 20, 2021

To save anybody’s googling time

Once you update you package deps you may face with the error mentioned in this note title:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ~/projects/semantic-release-toolkit/node_modules/zz/cjs.js
require() of ES modules is not supported.
require() of ~/projects/semantic-release-toolkit/node_modules/zz/cjs.js from ~/projects/semantic-release-toolkit/tt.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename cjs.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from ~/projects/semantic-release-toolkit/node_modules/zz/package.json.

Enter fullscreen mode

Exit fullscreen mode

Even though your code stopped working, this issue has positive context: the future is coming and some of your project’s deps has been shipped as ES module.

What’s wrong?

The short answer — es module brings top-level await, but require has no idea how to deal with it. Detailed explanation — announcing a new —experimental-modules.

How to fix?

There’re several strategies:

1. Follow the trend

Migrate to ES modules. Replace require with import.

// before
const { sync } = require('read-pkg-up')
// after
import { readPackageUpSync } from 'read-pkg-up'

Enter fullscreen mode

Exit fullscreen mode

Publish as esm. Add a special instruction to package.json

{
  "type": "module"
}

Enter fullscreen mode

Exit fullscreen mode

2. Stay on ES5

Wrap ES6 module(s) with esm adapter. Just like the documentation says:

// read-pkg-up-wrapper.js
require = require('esm')(module, {
  mode: 'all',
  cjs: {
    ... //
  },
  force: false,
  cache: false,
  await: false
})
module.exports = require('read-pkg-up')

Enter fullscreen mode

Exit fullscreen mode

NOTE It’s advisable to use patched esm that properly handles legacy (.js) extensions. See esm/issues/868 for details.

3. Take both.

Provide conditional export.
You’re able to split your code into esm and cjs versions.

// package.json
{
   ...
  "exports": {
    "import": "./es6entry.mjs",
    "require": "./es5entry.cjs"
  }
}

Enter fullscreen mode

Exit fullscreen mode

NOTE .cjs/.mjs file extension has matter.

This approach requires that your code to be refactored in some way:

  • Rewrite by hand with require and import syntax.
  • Recompile (TypeScript) separately with CommonJS and ES6 module options.
  • Wrap one version inside the other.
    • es6 in es5 (std/esm) as mentioned above
    • reexport es5 from es6
import cjsModule from './index.cjs'
export const name = cjsModule.name

Enter fullscreen mode

Exit fullscreen mode

Conditional export is especially important for a situation when you’re developing a package that needs ES6 deps, but its called by an external utility that uses legacy ES5 loading. For example, some-semrel-plugin depends from read-pkg-up@8 (es6), and is being invoked through require directive in semantic-release.

Related refs

  • EcmaScript-CommonJS Module Interop: The Missing Manual
  • Node Modules at War: Why CommonJS and ES Modules Can’t Get Along
  • Get Ready For ESM
  • Pure ESM package
  • Migrating from CommonJS to ESM
  • esm/issues/868
  • cjs to esm
  • https://stackoverflow.com/questions/57169793/error-err-require-esm-how-to-use-es6-modules-in-node-12
  • https://blog.logrocket.com/publishing-node-modules-typescript-es-modules/
  • https://blog.logrocket.com/es-modules-in-node-today/

Let’s team up together 🤝

We’re hiring for a Senior Full Stack Engineer to join the DEV team. Want the deets? Head here to learn more about who we’re looking for.

#node.js #typescript #es6-modules

Вопрос:

Я пытаюсь протестировать imagemin amp; imagemin-mozjpeg , поэтому я написал небольшой проект для этого.

индекс.ts

 import imagemin from 'imagemin';
import imageminMozjpeg from 'imagemin-mozjpeg';

(async () => {
  const files = await imagemin(["your-image.jpg"], {
    destination: "compressed-images",
    plugins: [
      imageminMozjpeg({quality: 50})
    ]
  });
  console.log(JSON.stringify(files, null, 1));
})();
 

main.ts

 require = require('esm')(module/* , options*/);
module.exports = require('./index');
 

Пакет.json

 {
"name": "1234",
"version": "1.0.0",
"revision": {
  "build_ts": 0,
  "git_commit": "dummy"
},
"description": "",
"main": "dist/main.js",
"author": "",
"license": "ISC",
"repository": {
  "type": "git",
  "url": ""
},
"scripts": {
  "start": "node ./dist/main.js",
  "build": "yarn build:js",
  "build:prod": "yarn run build:js",
  "build:types": "tsc --emitDeclarationOnly",
  "build:js": "babel . --out-dir ./dist --extensions ".ts" --ignore node_modules --ignore dist --source-maps",
  "build-ts": "tsc",
  "test": "jest --coverage --verbose",
  "lint-test": "npm run lint amp;amp; npm run test",
  "lint": "eslint -c .eslintrc.js --ext .ts ./src",
  "lint:fix": "eslint --fix -c .eslintrc.js --ext .ts ./src",
  "tslint": "tslint -c tslint.json --project tsconfig.json",
  "prettier": "prettier --write ./src/**/*.ts"
},
"dependencies": {
  "esm": "^3.2.25",
  "imagemin": "^8.0.0",
  "imagemin-mozjpeg": "^9.0.0"
},
"devDependencies": {
  "@babel/cli": "7.13.10",
  "@babel/core": "7.13.10",
  "@babel/plugin-proposal-class-properties": "7.13.0",
  "@babel/plugin-proposal-decorators": "7.13.5",
  "@babel/plugin-proposal-object-rest-spread": "7.13.8",
  "@babel/plugin-transform-runtime": "7.13.10",
  "@babel/preset-env": "7.13.10",
  "@babel/preset-typescript": "7.13.0",
  "@babel/runtime": "7.13.10",
  "@types/imagemin": "^7.0.1",
  "@types/imagemin-mozjpeg": "^8.0.1",
  "@typescript-eslint/eslint-plugin": "4.17.0",
  "@typescript-eslint/eslint-plugin-tslint": "4.17.0",
  "@typescript-eslint/parser": "4.17.0",
  "babel-plugin-transform-typescript-metadata": "0.3.2",
  "eslint": "7.21.0",
  "eslint-config-prettier": "^6.11.0",
  "eslint-plugin-jest": "^23.18.0",
  "eslint-plugin-jsdoc": "32.2.0",
  "prettier": "2.0.5",
  "ts-jest": "26.5.3",
  "ts-node": "^9.1.1",
  "ts-node-dev": "1.1.6",
  "tslint": "^6.1.3",
  "typescript": "4.2.3"
}


}
 

Я бегу:

yarn run build
yarn run start

и получите следующую ошибку:

 $ node ./dist/main.js
/testing-project/node_modules/imagemin/index.js:1
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /testing-project/node_modules/imagemin/index.js
require() of ES modules is not supported.
require() of /testing-project/node_modules/imagemin/index.js from /testing-project/dist/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /testing-project/node_modules/imagemin/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /testing-project/node_modules/imagemin/package.json.
 

Пожалуйста, посоветуйте, как я могу это решить, спасибо.

Ответ №1:

Проблема заключалась в сочетании различных конфигураций машинописного текста. Начал новый проект, и проблема была решена.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Parsing error loading custom advancement
  • Partition table error 105 found как исправить
  • Parsing error loading built in advancement
  • Partition table entries are not in disk order как исправить
  • Parsing error legacy octal literals are not allowed in strict mode

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии