jackieli123723 / jackieli123723.github.io

✅lilidong 个人博客
9 stars 0 forks source link

chalk esm 如何在commonjs使用 #81

Open jackieli123723 opened 2 years ago

jackieli123723 commented 2 years ago
const chalk = require("chalk");

 let log = `[${chalk.blue(
    formatted_date
  )}] ${method}:${url} ${status} ${chalk.red(
    durationInMilliseconds.toLocaleString() + "ms"
  )}`;

报错如下

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/runner/ExpressjsMiddlewarelogging/node_modules/chalk/source/index.js
require() of ES modules is not supported.
require() of /home/runner/ExpressjsMiddlewarelogging/node_modules/chalk/source/index.js from /home/runner/ExpressjsMiddlewarelogging/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 /home/runner/ExpressjsMiddlewarelogging/node_modules/chalk/source/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/runner/ExpressjsMiddlewarelogging/node_modules/chalk/package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1015:13)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at /home/runner/ExpressjsMiddlewarelogging/index.js:3:15
    at Script.runInContext (vm.js:130:18)
    at Object.<anonymous> (/run_dir/interp.js:209:20)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)Hint: hit control+c anytime to enter REPL.
 
jackieli123723 commented 2 years ago

fix-esm v1.0.1 Fixes ERR_REQUIRE_ESM errors so that you can require ESM modules from CommonJS

jackieli123723 commented 2 years ago

const chalk = require("fix-esm").require('chalk'); const symbols = require("fix-esm").require('log-symbols');

jackieli123723 commented 2 years ago

// let fetch = require("node-fetch") // const fetch = require('node-fetch').default not work // https://github.com/node-fetch/node-fetch const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args)); // cjs

jackieli123723 commented 2 years ago

应为chalk 改为了ems 导致了 chalk 不能正常使用

或者简单粗暴降级到: "chalk": "^4.0.0",