【问题标题】:How to properly bundle the React 17 library with new JSX transform as ES Module?如何将 React 17 库与新的 JSX 转换正确捆绑为 ES 模块?
【发布时间】:2022-07-11 10:20:21
【问题描述】:

我正在构建一个简单的 React 组件库,并且需要作为仅 ES 模块的包发布到 NPM。由于我使用的是 React 17,因此我使用了新的 JSX 转换。我使用汇总和打字稿来生成 ES 包。生成的 JS 文件如下所示:

// ./dist/index.js
import { jsx, jsxs } from 'react/jsx-runtime';
import { forwardRef } from 'react';
import { SVGIcon } from './SVGIcon.js';

const Add = forwardRef(function Add(props, ref) {
  return (jsx( /*  */));
});

const Bell = forwardRef(function Add(props, ref) {
  return (jsx( /*  */));
});

这看起来不错。 TypeScript 编译器正在将jsx-runtime 添加到生成的代码中:

import { jsx, jsxs } from 'react/jsx-runtime';

但是,当我尝试在另一个应用程序中使用此库时,就会出现问题。 Webpack 抱怨找不到'react/jsx-runtime'。确切的错误是这样的:

error - Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/hp/test/node_modules/react/jsx-runtime'
imported from /home/hp/test/node_modules/@hrp/icons/dist/index.js
Did you mean to import react/jsx-runtime.js?

它不会抱怨react。当我手动将导入模块的扩展名(添加.js 扩展名)更改为'react/jsx-runtime.js' 时,它就可以工作了。

那么,如何配置汇总或任何其他模块捆绑器来为从第三方模块导入的子路径添加适当的文件扩展名?

【问题讨论】:

  • 你解决了吗?
  • @Rainning,我没有。目前似乎没有任何干净的解决方案。
  • @HarshalPatil 你能包括你的 tsconfig 吗?
  • 你在使用汇总吗?网络包?
  • @caub 我没有像问题中所说的那样使用 rollup.js。虽然,我更喜欢普通的tsc,而不是任何捆绑器,因为我对纯 ES 模块感兴趣。

标签: javascript reactjs typescript webpack rollup


【解决方案1】:

我使用 Rollup output.paths 解决了这个问题。

output: {
  dir: './esm',
  format: 'esm',
  paths: {
    'react/jsx-runtime': path.resolve(
      './node_modules/react/jsx-runtime.js'
    ),
  },
  ...
}

【讨论】:

    猜你喜欢
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2022-12-28
    • 2018-07-06
    • 2020-08-02
    相关资源
    最近更新 更多