react-script:转译第三方 JSX 文件

react-script: Transpiling Third party JSX files

我正在使用 create-react-app 开发应用程序,并使用未编译的第三方模块,我将其中的 JSX 文件包含到我的项目中。

启动或构建时出现以下错误

******.jsx
Module parse failed: Unexpected token (12:25)
You may need an appropriate loader to handle this file type.

我的 React 应用程序没有弹出,也不想弹出。

不想从 react-script 中弹出

******.jsx
Module parse failed: Unexpected token (12:25)
You may need an appropriate loader to handle this file type.

示例代码 Link.jsx 在图书馆

import React from 'react';
import { string } from 'prop-types';
import './Link.scss';

const STATUS = {
  HOVERED: 'hovered',
  NORMAL: 'normal',
};

class Link extends React.Component {
  constructor(props) {
    super(props);

    this.onMouseEnter = this.onMouseEnter.bind(this);
    this.onMouseLeave = this.onMouseLeave.bind(this);

    this.state = {
      className: STATUS.NORMAL,
    };
  }

  onMouseEnter() {
    this.setState({ className: STATUS.HOVERED });
  }

  onMouseLeave() {
    this.setState({ className: STATUS.NORMAL });
  }

  render() {
    const { className } = this.state;
    const { page, children } = this.props;

    return (
      <a
        className={className}
        href={page}
        onMouseEnter={this.onMouseEnter}
        onMouseLeave={this.onMouseLeave}
      >
        {children}
      </a>
    );
  }
}

Link.propTypes = {
  page: string,
  children: string,
};

Link.defaultProps = {
  page: '#',
  children: '',
};

export default Link;

以上代码已发布到内部 npm 仓库并在应用程序中使用

App.jsx 申请中

import { Link} from '@myScope/myreactlib/Link'; // loaded from node_modules

App.jsx报错

在不弹出的情况下使用 create-react-app 时,您将对如何导入模块有一些限制。

如果它是您构建的自定义模块,则它需要位于您的 src 文件夹中,并且您使用相对于当前文件路径的路径导入它。例如:import MyComponent from './components/MyComponent

如果来自你已经用npmyarn添加的第三方依赖包(例如reactstrap@blueprintjs/core),则您只需指定包名称即可导入它。例如:import { Button } from 'reactstrap'

在你的情况下,听起来你的 node_modules 文件夹中有一个子文件夹,它是你 没有 添加的包 npmyarn。虽然我怀疑是否建议以这种方式使用第三方包,但我假设您有充分的理由这样做。

由于无法看到您的整个设置,我建议您尝试以下解决方法:

  1. 在您的 src 文件夹中,创建指向包含第三方包的文件夹的符号链接。例如(在项目的 src 文件夹中):
ln -s ../node_modules/@myScope/myreactlib myreactlib
  1. 然后,在您的 App.jsx 文件中,执行:
import { Link } from './myreactlib/Link'

附加信息: