Monday, 11 February 2019

Error with JSX in my React Library when Switching to Preact

I have a really simple React library that I use with my own state management. It's just a Higher Order Component:

import React from 'react';
/**
 * 
 * @param {Object} state - Reference to SubState instance 
 * @param {Object} chunk  - object of props you want maps to from state to props
 */
const connect = (state, chunk)=> Comp => props =>{
    const newProps = {};
    for (let key in chunk){
        newProps[key] = state.getProp(chunk[key]);
    }
    return (<Comp {...newProps} {...props} />)
};

export {
    connect
}

I can publish the library this way and I will get a syntax error about being unable to parse < in the JSX.

So I run the code through babel

//.babelrc

{
    "presets": ["@babel/preset-env","@babel/preset-react"]
}

using this webpack config

const path = require('path');
module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname),
        filename: 'index.js',     
        library: 'substateConnect',
        libraryTarget: 'umd'
    },
    module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: ["babel-loader"]
          }
        ]
      },
}

this is the dependency and publish section of my package.json

 "devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.2",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "react": "^16.5.0",
    "react-dom": "^16.5.0"
  },
  "files": [
    "index.js",
    "index.map",
    "src/index.js"  
  ],
  "dependencies": {
    "@babel/preset-react": "^7.0.0",
    "substate": "^4.0.0",
    "webpack": "^4.17.2",
    "webpack-cli": "^3.1.0"
  }

I'm using preact-compat per the website and still getting <undefined></undefined> https://github.com/developit/preact-compat#usage-with-webpack

Currently, running this through babel outputs react in the library and my library and Preact labels any HOC that use this library as <undefined></undefined>

IF I publish the un-babel'd code and it is simply the source cope at the top written in new ECMAScript, I get an unable to parse error on the < in the JSX.

However, if I were to reference the library NOT through node_modules but in a developer made files like myLibrary.js and use the un-babel'd code, it works.

How do I manage my dependencies correctly? Should React be a peerDependecy? Furthermore, how to get this library to work from the node_modules directory for BOTH React AND Preact?



from Error with JSX in my React Library when Switching to Preact

No comments:

Post a Comment