-2

I'm writing this app using React and I was trying to package it up in NPM to use it in a different project.

I have as my index.js entrypoint something like this:

import { MyReactComponent } from './mypackage';
export { MyReactComponent } // for 3rd party packages who use this package

// to display the component when I'm running this package to test out changes
ReactDOM.render(
    <MyReactComponent />,
    document.getElementById('react')
)

If I want to use my package in another library, I should delete the ReactDOM.render() part because that's causing problems. But I'd still like the render part when I'm testing changes "standalone".

Is there something I can do? I think I want a setup similar to Python's if __name__ == "__main__": paradigm. I'm also willing to switch to the React way of doing it, if there is one.

  • Why not have a separate entry point for rendering it in dev? That entry point can then use the same export you expect your consumers to, so your testing is more representative of usage. – jonrsharpe Aug 17 '19 at 08:04
  • You mean to add multiple entry points in the webpack config? Let me try that. Thanks! – Cory Parsnipson Aug 17 '19 at 18:46

1 Answers1

0

In hindsight, this question could have been better narrowed down to be about Webpack configuration, as it appears that Reactjs does not specify or care how you package things up.

I added multiple entrypoints to my Webpack config as you can see in the webpack.config.js excerpt below:

entry: {
   main: './src/index.js',
   standalone: './src/index-standalone.js'
},

And the contents of index.js and index-standalone.js look like this:

index.js

import React from 'react'
import ReactDOM from 'react-dom'

import { MyReactComponent } from './mypackage';
export { MyReactComponent }

index-standalone.js

import React from 'react'
import ReactDOM from 'react-dom'

import { MyReactComponent } from './mypackage';

ReactDOM.render(
   <MyReactComponent />,
   document.getElementById('react')
);

The intention is to have the main entry point not be hardcoded to insert a react element anywhere. This is meant for 3rd party users to import the package and do whatever they please.

The standalone entry point has the original code to interact with my test harness.