首页 文章

与另一个项目一起开发React组件库(Webpack / Babel问题)

提问于
浏览
1

我正在 Build 一个开发环境,我希望能够在我的主应用程序中使用它们的同时开发React组件库 .

我在我的应用程序目录中运行 npm link ../path/to/lib 并成功将库符号链接到应用程序 node_modules . 但是,我似乎对如何设置Babel和/或Webpack以使代码能够正确编译有一些误解 . 请注意,库和主应用程序都是用ES6编写的,主应用程序是一个弹出的Create-React-App应用程序 .

目前,该库的根目录下有一个 index.js 文件,它只是导出一个React组件:

export {default as Button} from './components/button/Button.jsx'

这是 Button.jsx 的样子:

import React, { PropTypes } from 'react'
import classnames from 'classnames'

export default class Button extends React.Component {

    render() {

        let classes = classnames({
          'primary-button': true,
          'primary-button-': this.props.type == '',
          'primary-button': this.props.elevation == 2,
          'primary-button': this.props.elevation >= 3,
        });

        return (
            <a className={classes}>
                {this.props.children}
            </a>
        )
    }
}

我甚至需要或不需要,但在尝试调试此问题时,我将 .babelrc 文件添加到库的根目录:

{
  "presets": ["es2015", "react"],
  "plugins": ["transform-class-properties"]
}

当我尝试将 Button 组件导入主应用程序中的组件(使用 import {Button} from 'lib' )时,出现以下错误:

Button.jsx Unexpected token (26:3)
You may need an appropriate loader to handle this file type.
| 
|       return (
|           <a className={classes}>
|                 {this.props.children}
|           </a>

问题:

  • 如何解决此错误?假设我的配置错误,我需要更改什么?库本身是否需要Webpack设置?我是否需要更改主应用程序的webpack配置?

  • 虽然使用 npm link 对库进行符号链接正确地将其添加到主应用程序 node_modules 目录,但它不会将其附加到 package.json . 我该如何正确添加它?此功能于2011年提出,但尚未完全解决:https://github.com/npm/npm/issues/1166

谢谢!

1 回答

  • 2

    使用默认的Create React App webpack配置,依赖项/ node_modules将不会被提供给babel,它假定依赖项导出已转换的构建 .

    有两种方法可以解决这个问题:

    1:将组件库添加到babel-loader中包含的内容中 . 看看webpack module config,你会看到 src 具体是 include d(通过一个变量),你可以在那里添加你的库 .

    这是短期内更容易的解决方案

    2:出口转换组件 . 为组件库设置构建过程,该过程创建Babeled的每个组件的 dist 版本,并将index.js指向这些组件 .

    从长远来看,这可能更容易,因为它可以使您的库更具可移植性,您可以轻松地开源或在许多项目中使用它,而无需更改每个项目的配置 .

相关问题