How to move to ESM

I am using Egg framework for my NodeJs(v14.15.4) application

I want to use latest version of p-debounce library, the package is now pure ESM, Instead of const pDebounce = require('p-debounce') I must use import pDebounce from 'p-debounce' that not works on EggJs

If I use import

      (node:10636) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
test.js:5
import pDebounce from 'p-debounce'
^^^^^^

SyntaxError: Cannot use import statement outside a module

If I use require

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

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: .\node_modules\p-debounce\index.js
require() of ES modules is not supported.
require() of .\node_modules\p-debounce\index.js from .\test.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 .\node_modules\p-debounce\package.json.

If I add "type": "module" in the package.json

      const path = require('path');
             ^

ReferenceError: require is not defined

I have many require in my application and not want to change all to import at the moment

  1. What is "type": "module" in the package.json ?
  2. How can I fix the error?

2 ответа

Решение

You seem to be overlooking a particular point in the changelog you linked:

If you cannot move to ESM yet, don't upgrade to this version.

As you've pointed out, your application has already progressed significantly, and you have many require that you do not want to change at the moment. There is no need to upgrade to the latest version of p-debounce at this time, according to your needs.

When you do decide to migrate to ESM format, in order to upgrade individual files one at a time, you can use the <tcode id="304193"></tcode> extension to treat the code as an ECMAScript module.

Модули ES - это будущее.

В модулях ES есть способ потребовать модуль common.js. С использованием createRequire

РАБОЧИЙ ПРИМЕР

axios-curlirize — это модуль ES, и axios поддерживает оба.

      import { createRequire } from 'module';

const require = createRequire(import.meta.url);

const axios = require('axios');

import curlirize from 'axios-curlirize';

curlirize(axios);


const { data } = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
console.log(data)

Используя модули ES, вы можете использовать ожидание верхнего уровня без функции.

Другие вопросы по тегам