create-react-app 为CJS文件添加支持

o4hqfura  于 2个月前  发布在  React
关注(0)|答案(7)|浏览(43)

描述bug

如果一个依赖项包含一个 .cjs 文件,那么由于默认的webpack配置,该文件不会被babel处理,这意味着它将不会被加载。此外,在需要时,一些 cjs 文件也没有被排除: #11889

你是否尝试恢复你的依赖关系?

尝试过,但没有帮助

你在用户指南中搜索了哪些术语?

CJS,ESM,commonjs

环境

Environment Info:p@5.0.1
Ok to proceed? (y) y
  current version of create-react-app: 5.0.12c87c: timing idealTree:#root Completed in 1377ms
  running from /home/fryorcraken/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app

  System:
    OS: Linux 5.18 Fedora Linux 36 (Workstation Edition)
    CPU: (12) x64 Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
  Binaries:
    Node: 16.17.0 - ~/.nvm/versions/node/v16.17.0/bin/node
    Yarn: 1.22.19 - ~/.yarn/bin/yarn
    npm: 8.15.0 - ~/.nvm/versions/node/v16.17.0/bin/npm
  Browsers:
    Chrome: 104.0.5112.101
    Firefox: 103.0.2
  npmPackages:
    react: Not Found
    react-dom: Not Found
    react-scripts: Not Found
  npmGlobalPackages:
    create-react-app: Not Found

重现步骤

使用任何包含 *.cjs 文件的npm包。

预期行为

.cjs 文件正确加载,其中定义的函数、变量和类可用。

实际行为

.cjs 文件未加载,其中定义的函数、变量和类不可用。

可复现的演示

我不认为这是必要的,因为至少有5个PR已打开以修复此问题:

相关问题

l5tcr1uw

l5tcr1uw1#

这对我来说打破了几个不同的软件包。我需要进去直接修改 webpack.config.js 以修复它。如果能引起一些关注,那就太好了。在此之前,CRA 需要被分叉...
这个问题在 2020 年就被引用回来了,但由于某种原因被关闭为已完成:#8754

jaxagkaj

jaxagkaj2#

对于需要CJS支持的任何人,请添加react-app-rewired并在项目根目录下添加一个名为config-overrides.js的文件,内容如下:

const getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');

const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';

module.exports = function override(config, webpackEnv) {
  console.log('overriding webpack config...');

  const isEnvDevelopment = webpackEnv === 'development';
  const isEnvProduction = webpackEnv === 'production';
  const loaders = config.module.rules[1].oneOf;

  loaders.splice(loaders.length - 1, 0, {
    test: /\.(js|mjs|cjs)$/,
    exclude: /@babel(?:\/|\\{1,2})runtime/,
    loader: require.resolve('babel-loader'),
    options: {
      babelrc: false,
      configFile: false,
      compact: false,
      presets: [
        [
          require.resolve('babel-preset-react-app/dependencies'),
          { helpers: true },
        ],
      ],
      cacheDirectory: true,
      // See #6846 for context on why cacheCompression is disabled
      cacheCompression: false,
      // @remove-on-eject-begin
      cacheIdentifier: getCacheIdentifier(
        isEnvProduction
          ? 'production'
          : isEnvDevelopment && 'development',
        [
          'babel-plugin-named-asset-import',
          'babel-preset-react-app',
          'react-dev-utils',
          'react-scripts',
        ]
      ),
      // @remove-on-eject-end
      // Babel sourcemaps are needed for debugging into node_modules
      // code.  Without the options below, debuggers like VSCode
      // show incorrect code and set breakpoints on the wrong lines.
      sourceMaps: shouldUseSourceMap,
      inputSourceMap: shouldUseSourceMap,
    },
  });

  return config;
};

然后用以下内容替换您在package.json中的react-scripts脚本:

"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",

它为我解决了问题。

bnlyeluc

bnlyeluc3#

对于需要CJS支持的任何人,请添加react-app-rewired并在项目根目录下添加一个名为config-overrides.js的文件,内容如下:
我建议使用https://github.com/dilanx/craco/,它维护得更好,提供更多的灵活性。

ih99xse1

ih99xse14#

@dben89x,感谢提供的解决方法。我会尝试将其适配到craco。你能解释一下这个解决方法是如何工作的吗?可能是我下午头脑迟钝,但我很难理解发生了什么。

2guxujil

2guxujil5#

我可以确认这个问题,并提供一个解决方法来证明。将CRA更新到包含CJS会更好。
当我在CRA应用的node_modules中修改webpack.config.js(将cjs添加到mix中)时,我不再在加载使用.cjs的依赖项时收到undefined错误。

btxsgosb

btxsgosb6#

我修改了@nyan-left的解决方法,以便与craco一起使用,它解决了我的问题:

// craco.config.ts
export default {
  webpack: {
    configure: config => ({
      ...config,
      module: {
        ...config.module,
        rules: config.module.rules.map(rule => {
          if (rule.oneOf instanceof Array) {
            // eslint-disable-next-line no-param-reassign
            rule.oneOf[rule.oneOf.length - 1].exclude = [
              /\.(js|mjs|jsx|cjs|ts|tsx)$/,
              /\.html$/,
              /\.json$/,
            ];
          }
          return rule;
        }),
      },
    }),
  },
};

然而,我认为这是create-react-app的一个bug,这个问题是有效的,而且在这个问题中提到的许多PR中的一个将是解决它的更好方法。

qcuzuvrc

qcuzuvrc7#

你好。我花了几个小时解决了一个解释性错误信息。我试图在用create-react-app构建的宿主项目中使用依赖于react-tooltip的我的包。

按照上述解决方法,我的项目可以正常工作,但是我们有大约20个项目依赖于我们的自定义包,它们都是用create-react-app构建的。

相关问题