用create-react-app创建的react组件,发布到npm再到其它项目引用报错,如何解决?

Failed to compile
./~/react-cd-player/src/containers/ReactCdPlayer.js
Module parse failed: /Users/zhangwei/Work/Github/wulingmei/node_modules/react-cd-player/src/containers/ReactCdPlayer.js Unexpected token (46:16)
You may need an appropriate loader to handle this file type.
|         this.state.audio.addEventListener('timeupdate',this.onTimeUpdate)
|     }
|     onTimeUpdate=()=>{
|         console.log('ontimeupdate')
|         const ratio = this.state.audio.currentTime / this.state.audio.duration * 100;

我在想是不是引用之后不支持箭头函数,但是create-react-app是支持的啊,请问如何解决

阅读 4.9k
3 个回答

create-react-app目的是为了创建React项目,它封装了很多为项目使用的特性,不建议用它来做普通的React组件的开发。create-react-app 的webpack配置是封装到了react-script里面,你无法直接修改。你现在引入的组件里还有ES6的语法,这就对使用你组件的环境提出了特殊要求。如果你的组件是要发布到npm给其他人使用,你build时,就应该把ES6的语法全部转成ES5的语法,这样才有通用性。

估计是发布的项目有jsx,不通用了,配置webpack的时候,不要把node_modules排除,不然node_modules中的jsx无法编译。

module: {
        rules: [{
            test: /\.jsx?$/, 
            //exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015',  'stage-0', 'react'],
                plugins:['transform-runtime']
            }
        }]
    },

做一个靠谱点的项目发布给别人用的,肯定要编译成es5。。另外这cd界面似曾相识,难道不是树树的?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题