preactjs / preact-compat

ATTENTION: The React compatibility layer for Preact has moved to the main preact repo.
http://npm.im/preact-compat
MIT License
949 stars 148 forks source link

Reverse compatibility layer #489

Closed edygarOliveira closed 4 years ago

edygarOliveira commented 6 years ago

Is there any layer to consume preact-specific components in React? I mean, some module which would polyfill the h to createElement, render and so on?

developit commented 6 years ago

Here's a basic implementation:

react-compat.js:

import { createElement, Children, cloneElement, Component as ReactComponent } from 'react';
import { render, findDOMNode } from 'react-dom';

const EMPTY_ARR = [];

function h() {
  const vnode = createElement.apply(this, arguments);
  vnode.attributes = vnode.props;
  vnode.nodeName = vnode.tag;
  vnode.children = Children.toArray(vnode.children || vnode.props.children || EMPTY_ARR);
  return vnode;
}

class Component extends ReactComponent {
  get base() {
    return findDOMNode(this);
  }
}

export default { render, h, createElement: h, cloneElement, Component };
export { render, h, h as createElement, cloneElement, Component };
Ivy4 commented 6 years ago

@developit where would this go in the build process?

developit commented 6 years ago
resolve: {
  alias: {
    preact: './path/to/react-compat.js'
  }
}
hadim commented 5 years ago

Could you give a more complete example? I am having trouble to make it work.

My React project is setup with react-scripts, I have added your script react-compat.js and added the following:

"module": {
    "exports": {
      "settings": {
        "import/resolver": {
          "alias": {
            "preact:": "./src/react-compat.js"
          }
        }
      }
    }
  }

to the .eslintrc file and also added the lib eslint-import-resolver-alias.

I am not sure that setup is correct and I have an error trying to render the preact component:

Uncaught (in promise) Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
hadim commented 5 years ago

(note that the project uses React 16.5)