You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack项目集成TailwindCSS时遇ERR_REQUIRE_ESM错误求助

解决Webpack集成TailwindCSS时的ERR_REQUIRE_ESM错误

方案1:锁定string-width为CommonJS兼容版本

string-width v7+改为了纯ES模块,而你的依赖cliui仍用CommonJS的require()加载它,导致冲突。可以强制指定string-width为兼容的CommonJS版本:

  • 若使用npm,在package.json中添加overrides字段:
"overrides": {
  "string-width": "6.1.0"
}
  • 若使用yarn,添加resolutions字段:
"resolutions": {
  "string-width": "6.1.0"
}
  • 执行以下命令重装依赖:
rm -rf node_modules package-lock.json
npm install

方案2:降级yargs到兼容版本

你的webpack配置依赖yargs,高版本yargs会引入依赖ESM模块的cliui版本。降级yargs到17.x版本(兼容CommonJS生态):

npm install yargs@17.7.2 --save-dev

同样删除node_modules和锁文件后重装依赖。

方案3:将webpack配置转为ESM格式(可选)

如果上述方案无效,可将webpack配置改为ES模块格式:

  1. 重命名webpack.config.js为webpack.config.mjs
  2. 修改配置代码为ESM语法:
import webpack from "webpack";
import path from "path";
import yargs from "yargs";
import pkg from "./package.json" assert { type: "json" };
import { fileURLToPath } from "url";
import { dirname } from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const env = yargs.argv.env;

let libraryName = "test";
let outputFile, mode;

if (env === "build") {
  mode = "production";
  outputFile = libraryName + ".min.js";
} else {
  mode = "development";
  outputFile = libraryName + ".js";
}

const config = {
  mode: mode,
  entry: path.resolve(__dirname, "src/index.js"),
  devtool: "source-map",
  output: {
    path: path.resolve(__dirname, "public/lib"),
    filename: outputFile,
    library: libraryName,
    libraryTarget: "umd",
    umdNamedDefine: true,
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: ["babel-loader"],
      },
      {
        test: /\.css$/i,
        include: path.resolve(__dirname, "src"),
        use: ["style-loader", "css-loader", "postcss-loader"],
      },
    ],
  },
  resolve: {
    modules: [path.resolve(__dirname, "./node_modules"), path.resolve(__dirname, "./src")],
    extensions: ["*", ".js", ".jsx"],
  },
};

export default config;
  1. 运行webpack时指定配置文件:
webpack --config webpack.config.mjs

额外优化:清理过时的Babel配置

你的.babelrc中@babel/preset-es2015已废弃,建议移除,保留@babel/preset-env即可覆盖ES2015及更高版本的兼容:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": ["babel-plugin-add-module-exports"]
}

内容的提问来源于stack exchange,提问作者Rishav Bharti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:32:15