如何解决Webpack情况下的“[ERR_REQUIRE_ESM]: require() of ES Module”错误?

huangapple go评论69阅读模式
英文:

How to solve " [ERR_REQUIRE_ESM]: require() of ES Module" for Webpack case?

问题

I tried to import the w3c-html-validator but got the error

> Error [ERR_REQUIRE_ESM]: require() of ES Module D:(...)\node_m
> odules\w3c-html-validator\node_modules\chalk\source\index.js from
> D:(...)\node_modules\w3c-html-validator\dist\w3c-html-validator.umd.cjs
> not supported.

Looks like this problem is with chalk, the dependency of w3c-html-validator.

I am using the Webpack with webpack-node-externals.
Thank to it, export/import keywords are available even though the output is the CommonJS and indented to be executed by plain Node.js. It should be the specific solution for this case, not just "add type: module to your package.json".

If possible, I want to avoid the adding of type: module to the package.json because it could cause other errors. Currently, I have about 30 dependencies (see the appendix) and neither of them requires type: module.

Appendix

Webpack setup

import Webpack from "webpack";
import Path from "path";

import NodeExternalsPlugin from "webpack-node-externals";
import ForkTypeScriptCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
import ESLintPlugin from "eslint-webpack-plugin";

import type { ArbitraryObject } from "@yamato-daiwa/es-extensions";


export default function generateConfiguration(
  _environment: ArbitraryObject, commandArguments: ArbitraryObject
): Webpack.Configuration {

  const SOURCE_CODE_ROOT_DIRECTORY_ABSOLUTE_PATH: string = Path.resolve(__dirname, "Source");

  const __IS_DEVELOPMENT_BUILDING_MODE__: boolean = commandArguments.mode === "development";
  const __IS_PRODUCTION_BUILDING_MODE__: boolean = commandArguments.mode === "production";

  return {

    target: "node",

    context: SOURCE_CODE_ROOT_DIRECTORY_ABSOLUTE_PATH,
    entry: { EntryPoint: "./EntryPoint.ts" },

    output: {
      path: __dirname,
      filename: "[name].js",
      library: {
        type: "commonjs"
      }
    },

    /* [ Theory ] Valid non-undefined values are only "development", "production" and "none". */
    mode: __IS_DEVELOPMENT_BUILDING_MODE__ ? "development" : "production",
    watch: __IS_DEVELOPMENT_BUILDING_MODE__,
    optimization: {
      emitOnErrors: __IS_DEVELOPMENT_BUILDING_MODE__,
      minimize: __IS_PRODUCTION_BUILDING_MODE__
    },

    node: {
      __dirname: false
    },

    devtool: false,

    externals: [
      NodeExternalsPlugin({
        allowlist: [ "rev-hash" ]
      })
    ],

    module: {
      rules: [
        {
          test: /\.ts$/u,
          loader: "ts-loader",
          options: {
            /* [ Theory ] 'ForkTypeScriptCheckerWebpackPlugin' will execute the type checking. */
            transpileOnly: true
          }
        }
      ]
    },

    resolve: {
      extensions: [ ".ts", ".js" ],
      alias: { /* ... */ }
    },

    plugins: [
      new Webpack.DefinePlugin({
        __IS_DEVELOPMENT_BUILDING_MODE__,
        __IS_PRODUCTION_BUILDING_MODE__
      }),
      new ForkTypeScriptCheckerWebpackPlugin({
        typescript: {
          /* [ Theory ] The default value is 'context', but the 'tsconfig.json' is 1 level above 'context'. */
          configFile: Path.resolve(__dirname, "tsconfig.json")
        }
      }),
      new ESLintPlugin({
        extensions: [ "js", "ts" ],
        failOnWarning: __IS_PRODUCTION_BUILDING_MODE__
      })
    ]
  };
}

Current dependencies

{
  "dependencies": {
    "@typescript-eslint/eslint-plugin": "5.57.0",
    "@typescript-eslint/parser": "5.57.0",
    "@vue/compiler-sfc": "3.2.47",
    "@webdiscus/pug-loader": "2.10.4",
    "@yamato-daiwa/es-extensions": 1.6.9,
    "@yamato-daiwa/es-extensions-nodejs": "1.6.0-alpha.9",
    "@yamato-daiwa/style_guides": "0.0.47",
    "access-sniff": "3.2.0",
    "autoprefixer": "10.4.14",
    "browser-sync": "2.27.11",
    "cheerio": "1.0.0-rc.1",
    "css-loader": "6.7.3",
    "cssnano": "5.1.14",
    "eslint": "8.37.0",
    "eslint-plugin-import": "2.27.5",
    "eslint-plugin-node": "11.1.0",
    "eslint-webpack-plugin": "4.0.0",
    "fork-ts-checker-webpack-plugin": "7.3.0",
    "glob": "7.2.0",
    "gulp": "4.0.2",
    "gulp-data": "1.3.1",
    "gulp-debug": "4.0.0",
    "gulp-html-prettify": "0.0.1",
    "gulp-if": "3.0.0",
    "gulp-imagemin": "7.1.0",
    "gulp-intercept": "0.1.0",
    "gulp-plumber": "1.2.1&quot

<details>
<summary>英文:</summary>

I tried to import the [w3c-html-validator][1] but got the error 

&gt; Error [ERR_REQUIRE_ESM]: require() of ES Module D:\(...)\node_m
&gt; odules\w3c-html-validator\node_modules\chalk\source\index.js from
&gt; D:\(...)\node_modules\w3c-html-validator\dist\w3c-html-validator.umd.cjs
&gt; not supported.

Looks like this problem is with [chalk][2], the dependency of **w3c-html-validator**.

I am using the Webpack with [webpack-node-externals][3]. 
Thank to it, `export`/`import` keywords are available even though the output is the CommonJS and indented to be executed by plain Node.js. It should be the specific solution for this case, not just &quot;add `type: module` to your `package.json`&quot;.

If possible, I want to avoid the adding of `type: module` to the **package.json** because it could cause other errors. Currently, I have about 30 dependencies (see the appendix) and neither of them requires `type: module`.


## Appendix
### Webpack setup

```typescript
import Webpack from &quot;webpack&quot;;
import Path from &quot;path&quot;;

import NodeExternalsPlugin from &quot;webpack-node-externals&quot;;
import ForkTypeScriptCheckerWebpackPlugin from &quot;fork-ts-checker-webpack-plugin&quot;;
import ESLintPlugin from &quot;eslint-webpack-plugin&quot;;

import type { ArbitraryObject } from &quot;@yamato-daiwa/es-extensions&quot;;


export default function generateConfiguration(
  _environment: ArbitraryObject, commandArguments: ArbitraryObject
): Webpack.Configuration {

  const SOURCE_CODE_ROOT_DIRECTORY_ABSOLUTE_PATH: string = Path.resolve(__dirname, &quot;Source&quot;);

  const __IS_DEVELOPMENT_BUILDING_MODE__: boolean = commandArguments.mode === &quot;development&quot;;
  const __IS_PRODUCTION_BUILDING_MODE__: boolean = commandArguments.mode === &quot;production&quot;;

  return {

    target: &quot;node&quot;,

    context: SOURCE_CODE_ROOT_DIRECTORY_ABSOLUTE_PATH,
    entry: { EntryPoint: &quot;./EntryPoint.ts&quot; },

    output: {
      path: __dirname,
      filename: &quot;[name].js&quot;,
      library: {
        type: &quot;commonjs&quot;
      }
    },

    /* [ Theory ] Valid non-undefined values are only &quot;development&quot;, &quot;production&quot; and &quot;none&quot;. */
    mode: __IS_DEVELOPMENT_BUILDING_MODE__ ? &quot;development&quot; : &quot;production&quot;,
    watch: __IS_DEVELOPMENT_BUILDING_MODE__,
    optimization: {
      emitOnErrors: __IS_DEVELOPMENT_BUILDING_MODE__,
      minimize: __IS_PRODUCTION_BUILDING_MODE__
    },

    node: {
      __dirname: false
    },

    devtool: false,

    externals: [
      NodeExternalsPlugin({
        allowlist: [ &quot;rev-hash&quot; ]
      })
    ],

    module: {
      rules: [
        {
          test: /\.ts$/u,
          loader: &quot;ts-loader&quot;,
          options: {
            /* [ Theory ] &#39;ForkTypeScriptCheckerWebpackPlugin&#39; will execute the type checking. */
            transpileOnly: true
          }
        }
      ]
    },

    resolve: {
      extensions: [ &quot;.ts&quot;, &quot;.js&quot; ],
      alias: { /* ... */ }
    },

    plugins: [
      new Webpack.DefinePlugin({
        __IS_DEVELOPMENT_BUILDING_MODE__,
        __IS_PRODUCTION_BUILDING_MODE__
      }),
      new ForkTypeScriptCheckerWebpackPlugin({
        typescript: {
          /* [ Theory ] The default value is &#39;context&#39;, but the &#39;tsconfig.json&#39; is 1 level above &#39;context&#39;. */
          configFile: Path.resolve(__dirname, &quot;tsconfig.json&quot;)
        }
      }),
      new ESLintPlugin({
        extensions: [ &quot;js&quot;, &quot;ts&quot; ],
        failOnWarning: __IS_PRODUCTION_BUILDING_MODE__
      })
    ]
  };
}

Current dependencies

{
  &quot;dependencies&quot;: {
    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;5.57.0&quot;,
    &quot;@typescript-eslint/parser&quot;: &quot;5.57.0&quot;,
    &quot;@vue/compiler-sfc&quot;: &quot;3.2.47&quot;,
    &quot;@webdiscus/pug-loader&quot;: &quot;2.10.4&quot;,
    &quot;@yamato-daiwa/es-extensions&quot;: 1.6.9,
    &quot;@yamato-daiwa/es-extensions-nodejs&quot;: &quot;1.6.0-alpha.9&quot;,
    &quot;@yamato-daiwa/style_guides&quot;: &quot;0.0.47&quot;,
    &quot;access-sniff&quot;: &quot;3.2.0&quot;,
    &quot;autoprefixer&quot;: &quot;10.4.14&quot;,
    &quot;browser-sync&quot;: &quot;2.27.11&quot;,
    &quot;cheerio&quot;: &quot;1.0.0-rc.1&quot;,
    &quot;css-loader&quot;: &quot;6.7.3&quot;,
    &quot;cssnano&quot;: &quot;5.1.14&quot;,
    &quot;eslint&quot;: &quot;8.37.0&quot;,
    &quot;eslint-plugin-import&quot;: &quot;2.27.5&quot;,
    &quot;eslint-plugin-node&quot;: &quot;11.1.0&quot;,
    &quot;eslint-webpack-plugin&quot;: &quot;4.0.0&quot;,
    &quot;fork-ts-checker-webpack-plugin&quot;: &quot;7.3.0&quot;,
    &quot;glob&quot;: &quot;7.2.0&quot;,
    &quot;gulp&quot;: &quot;4.0.2&quot;,
    &quot;gulp-data&quot;: &quot;1.3.1&quot;,
    &quot;gulp-debug&quot;: &quot;4.0.0&quot;,
    &quot;gulp-html-prettify&quot;: &quot;0.0.1&quot;,
    &quot;gulp-if&quot;: &quot;3.0.0&quot;,
    &quot;gulp-imagemin&quot;: &quot;7.1.0&quot;,
    &quot;gulp-intercept&quot;: &quot;0.1.0&quot;,
    &quot;gulp-plumber&quot;: &quot;1.2.1&quot;,
    &quot;gulp-postcss&quot;: &quot;9.0.1&quot;,
    &quot;gulp-pug&quot;: &quot;5.0.0&quot;,
    &quot;gulp-sourcemaps&quot;: &quot;3.0.0&quot;,
    &quot;gulp-stylus&quot;: &quot;2.7.1&quot;,
    &quot;imagemin-pngquant&quot;: &quot;9.0.2&quot;,
    &quot;json5-loader&quot;: &quot;4.0.1&quot;,
    &quot;minimatch&quot;: &quot;5.1.1&quot;,
    &quot;node-notifier&quot;: &quot;10.0.1&quot;,
    &quot;prettier&quot;: &quot;2.8.7&quot;,
    &quot;pug-lint&quot;: &quot;2.6.0&quot;,
    &quot;pug-plain-loader&quot;: &quot;1.1.0&quot;,
    &quot;rev-hash&quot;: &quot;4.0.0&quot;,
    &quot;stlint&quot;: &quot;1.0.65&quot;,
    &quot;stream-combiner2&quot;: &quot;1.1.1&quot;,
    &quot;style-loader&quot;: &quot;3.3.1&quot;,
    &quot;stylus-loader&quot;: &quot;7.1.0&quot;,
    &quot;ts-loader&quot;: &quot;9.4.2&quot;,
    &quot;vinyl&quot;: &quot;2.2.1&quot;,
    &quot;vue&quot;: &quot;3.2.47&quot;,
    &quot;vue-loader&quot;: &quot;17.0.1&quot;,
    &quot;vue-style-loader&quot;: &quot;4.1.3&quot;,
    &quot;vue-tsc&quot;: &quot;1.2.0&quot;,
    &quot;w3c-html-validator&quot;: &quot;1.3.3&quot;,
    &quot;webpack&quot;: &quot;5.76.2&quot;,
    &quot;webpack-node-externals&quot;: &quot;3.0.0&quot;,
    &quot;webpack-stream&quot;: &quot;7.0.0&quot;,
    &quot;worker-loader&quot;: &quot;3.0.8&quot;,
    &quot;yaml-loader&quot;: &quot;0.8.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@types/browser-sync&quot;: &quot;2.26.3&quot;,
    &quot;@types/cheerio&quot;: &quot;0.22.31&quot;,
    &quot;@types/cssnano&quot;: &quot;5.0.0&quot;,
    &quot;@types/glob&quot;: &quot;7.2.0&quot;,
    &quot;@types/gulp&quot;: &quot;4.0.10&quot;,
    &quot;@types/gulp-debug&quot;: &quot;2.0.32&quot;,
    &quot;@types/gulp-html-prettify&quot;: &quot;0.0.2&quot;,
    &quot;@types/gulp-if&quot;: &quot;0.0.34&quot;,
    &quot;@types/gulp-imagemin&quot;: &quot;8.0.1&quot;,
    &quot;@types/gulp-intercept&quot;: &quot;0.1.1&quot;,
    &quot;@types/gulp-plumber&quot;: &quot;0.0.33&quot;,
    &quot;@types/gulp-postcss&quot;: &quot;8.0.2&quot;,
    &quot;@types/gulp-sourcemaps&quot;: &quot;0.0.35&quot;,
    &quot;@types/gulp-stylus&quot;: &quot;2.7.4&quot;,
    &quot;@types/node&quot;: &quot;18.13.0&quot;,
    &quot;@types/node-notifier&quot;: &quot;8.0.2&quot;,
    &quot;@types/pug&quot;: &quot;2.0.6&quot;,
    &quot;@types/webpack-node-externals&quot;: &quot;2.5.3&quot;,
    &quot;@types/webpack-stream&quot;: &quot;3.2.12&quot;,
    &quot;ts-node&quot;: &quot;10.9.1&quot;,
    &quot;typescript&quot;: &quot;5.0.3&quot;,
    &quot;webpack-cli&quot;: &quot;5.0.1&quot;
  }
}

答案1

得分: 1

As you noted, the problem is that w3c-html-validator 使用了 chalk 的 ESM 版本。基本上,w3c-html-validator 的维护者错误地构建了 UMD/CJS 变体,试图 require 其自身的一个 ESM 依赖 🙃。

简单解决方案:将你的 w3c-html-validator 版本降级到 v0.8.1,该版本使用了 chalk 的 CommonJS 版本。

Babel 解决方案:在你的 webpack 构建中添加 babel-loader,将 chalk 依赖进行转译,将 import/export 转换为 require/module.exports,即 ESM 到 CJS。

你的 babel 配置应该类似于这样(如果你的 devDependencies 中没有的话,添加 @babel/preset-env):

{
  "presets": [
    ["@babel/preset-env", {
      "modules": "commonjs"
    }]
  ]
}

你的更新后的 webpack 配置应该包含类似于这样的内容:

module: {
  rules: [
    {
      test: /\.(t|j)sx?$/,
      include: filename => {
        return /node_modules\/chalk/.test(filename)
      },
      use: ['babel-loader']
    }
  ]
}
英文:

As you noted, the problem is that w3c-html-validator is using an ESM version of chalk. Basically, the maintainer of w3c-html-validator has built the UMD/CJS variant incorrectly by trying to require one of its own ESM dependencies 🙃.

Simple solution: Downgrade your version of w3c-html-validator to v0.8.1 which uses a CommonJS version of chalk.

Babel solution: Add babel-loader to your webpack build and transpile the chalk dependency to convert the import/export to require/module.exports, i.e. ESM to CJS.

Your babel config should look something like this (add @babel/preset-env if not already in your devDependencies):

{
  &quot;presets&quot;: [
    [&quot;@babel/preset-env&quot;, {
      &quot;modules&quot;: &quot;commonjs&quot;
    }]
  ]
}

Your updated webpack config should include something like this:

module: {
  rules: [
    {
      test: /\.(t|j)sx?$/,
      include: filename =&gt; {
        return /node_modules\/chalk/.test(filename)
      },
      use: [&#39;babel-loader&#39;]
    }
  ]
}

答案2

得分: 0

If the problem is your use of webpack-node-externals you might have luck with code like below.

Note that this solution relies on you knowing which modules are native dependencies (which should not take long to figure out.)

You might update the beginning of your config like this:

return {
    target: "node",
    externals: ['sharp', 'another-native-node-dep'], // Add your native dependency names to the array and remove my examples
    context: SOURCE_CODE_ROOT_DIRECTORY_ABSOLUTE_PATH,
    entry: { EntryPoint: "./EntryPoint.ts" },
英文:

If the problem is your use of webpack-node-externals you might have luck with code like below.

Note that this solution relies on you knowing which modules are native dependencies (which should not take long to figure out.)

You might update the beginning of your config like this:

return {
    target: &quot;node&quot;,
    externals: [&#39;sharp&#39;, &#39;another-native-node-dep&#39;], // Add your native dependency names to the array and remove my examples
    context: SOURCE_CODE_ROOT_DIRECTORY_ABSOLUTE_PATH,
    entry: { EntryPoint: &quot;./EntryPoint.ts&quot; },

huangapple
  • 本文由 发表于 2023年5月14日 10:15:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定