Cory Parsnipson
Cory Parsnipson

Reputation: 1

Conditional "test harness" code for my NPM package?

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.

Upvotes: -2

Views: 94

Answers (1)

Cory Parsnipson
Cory Parsnipson

Reputation: 1

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.

Upvotes: 0

Related Questions