Jamie Aden
Jamie Aden

Reputation: 981

exporting a react component as npm package

Says I want to share a simple react component in npm package, to let others use it, must I do this?

import SomeComponent from './components/SomeComponent';

module.exports = {
  SomeComponent: SomeComponent
}

reference https://github.com/alanbsmith/npm-example-module/blob/master/lib/index.js

In package.json of the project you can see the main file of the package is build/index.js, but why the author don't just export components/SomeComponent, but instead created a wrapper? I understand he use babel, it's to support the code for legacy browser but why use module.exports in this case?

Upvotes: 5

Views: 7329

Answers (1)

kingdaro
kingdaro

Reputation: 12018

If you're using es6 imports, you should use es6 exports as well for consistency.

import SomeComponent from './components/SomeComponent'
export { SomeComponent }

And in your package.json set the main field to the file after build. such as

{
   "main": "lib/index.js"
}

Then people can import it like this:

import { SomeComponent } from 'my-lib'

The example you're following looks really outdated, though, and doesn't follow a lot of good practices. Here's a more modern-looking solution that you'll probably have less trouble with.

Upvotes: 8

Related Questions