Taro: 在React项目中import @tarojs/components, 会报组件undefined的错误

Created on 2 Jul 2020  ·  6Comments  ·  Source: NervJS/taro


相关平台

H5

复现仓库

https://codesandbox.io/s/black-http-zj956?file=/src/App.js
浏览器版本: Chrome 83
使用框架: React

复现步骤

  1. 使用create-react-app初始化react项目
  2. 引入@tarojs/component中的View组件
  3. 编译之后Chrome显示报错
import React from "react";
import { View } from "@tarojs/components";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <View>123</View>
    </div>
  );
}

期望结果

正确的渲染View组件

实际结果

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

环境信息

Taro v3.0.2


  Taro CLI 3.0.2 environment info:
    System:
      OS: macOS 10.15.4
      Shell: 5.7.1 - /bin/zsh
    Binaries:
      Node: 14.4.0 - /usr/local/bin/node
      Yarn: 1.22.4 - /usr/local/bin/yarn
      npm: 6.14.4 - /usr/local/bin/npm

补充信息

import { View } from '@tarojs/components/dist-h5',不会报undefined的错,但是缺少了web component的实现

Most helpful comment

@craig00

/**
 * taro-h5的polyfill
 * 手动注册web components
 * 手动引入web componts的样式
 */
import { applyPolyfills, defineCustomElements } from '@tarojs/components/loader'
import '@tarojs/components/dist/taro-components/taro-components.css'

applyPolyfills().then(() => {
  defineCustomElements(window)
})

All 6 comments

@AlvinYuXT 先 alias 一下

https://github.com/NervJS/taro/blob/c2774b6965d9b134a94daf1e68272e3b5e638833/packages/taro-webpack-runner/src/config/dev.conf.ts#L109

alias之后会缺少web component的定义的。目前找到了一个hack的方法解决,手动把web component注册进去

@AlvinYuXT 你好 请问一下 手动把web component注册进去是怎么操作的呢 我也有个类似的需求想在react项目用taro组件

@craig00

/**
 * taro-h5的polyfill
 * 手动注册web components
 * 手动引入web componts的样式
 */
import { applyPolyfills, defineCustomElements } from '@tarojs/components/loader'
import '@tarojs/components/dist/taro-components/taro-components.css'

applyPolyfills().then(() => {
  defineCustomElements(window)
})

@AlvinYuXT 感谢大佬的指点

不过我发现 defineCustomElements 可以用 resourcesUrl 参数指定 chunk 资源加载的 url ,类似如下代码,结果没有生效,大佬们能给看一下吗

applyPolyfills().then(() => {
  defineCustomElements(window, {
      resourcesUrl: 'http://localhost:8080/static/'
  })
})

@AlvinYuXT @craig00 大佬们探索好了之后欢迎给 Taro 文档贡献 React 项目使用 taro 组件库的最佳实践哈~

Was this page helpful?
0 / 5 - 0 ratings

Related issues

afateg picture afateg  ·  3Comments

liu-dongyu picture liu-dongyu  ·  3Comments

zhuxianguo picture zhuxianguo  ·  3Comments

Zchary-Ma picture Zchary-Ma  ·  3Comments

rainbowMorelhahahah picture rainbowMorelhahahah  ·  3Comments