Giter Club home page Giter Club logo

create-react-library's Introduction

2022 Update

This tool is no longer actively maintained. I suggest using either tsup, tsdx, or microbundle.

Here's an article I wrote in April 2022 which should help you decide between these different tools.

create-react-library

CLI for creating reusable, modern React libraries using Rollup and create-react-app.

NPM Build Status JavaScript Style Guide

Intro

Features

  • Easy-to-use CLI
  • Handles all modern JS features
  • Bundles commonjs and es module formats
  • create-react-app for example usage and local dev
  • Rollup for bundling
  • Babel for transpiling
  • Jest for testing
  • Supports complicated peer-dependencies
  • Supports CSS modules
  • Optional support for TypeScript
  • Sourcemap creation
  • Thousands of public modules created
  • Thorough documentation 😍
  • Chinese docs by @monsterooo

Install globally

This package requires node >= 10.

npm install -g create-react-library

Usage with npx

npx create-react-library

(npx comes with npm 5.2+ and higher, see instructions for older npm versions)

Creating a New Module

create-react-library

Answer some basic prompts about your module, and then the CLI will perform the following steps:

  • copy over the template
  • install dependencies via yarn or npm
  • link packages together for local development
  • initialize local git repo

At this point, your new module should resemble this screenshot and is all setup for local development.

Development

Local development is broken into two parts (ideally using two tabs).

First, run rollup to watch your src/ module and automatically recompile it into dist/ whenever you make changes.

npm start # runs rollup with watch flag

The second part will be running the example/ create-react-app that's linked to the local version of your module.

# (in another tab)
cd example
npm start # runs create-react-app dev server

Now, anytime you make a change to your library in src/ or to the example app's example/src, create-react-app will live-reload your local dev server so you can iterate on your component in real-time.

Publishing to npm

npm publish

This builds commonjs and es versions of your module to dist/ and then publishes your module to npm.

Make sure that any npm modules you want as peer dependencies are properly marked as peerDependencies in package.json. The rollup config will automatically recognize them as peers and not try to bundle them in your module.

Deploying to Github Pages

npm run deploy

This creates a production build of the example create-react-app that showcases your library and then runs gh-pages to deploy the resulting bundle.

Use with React Hooks

If you use react-hooks in your project, when you debug your example you may run into an exception Invalid Hook Call Warning. This issue explains the reason, your lib and example use a different instance, one solution is rewrite the react path in your example's package.json to 'file:../node_modules/react' or 'link:../node_modules/react'.

Examples

Multiple Named Exports

Here is a branch which demonstrates how to use multiple named exports. The module in this branch exports two components, Foo and Bar, and shows how to use them from the example app.

Material-UI

Here is a branch which demonstrates how to make use of a relatively complicated peer dependency, material-ui. It shows the power of rollup-plugin-peer-deps-external which makes it a breeze to create reusable modules that include complicated material-ui subcomponents without having them bundled as a part of your module.

Boilerplate

The CLI is based on this boilerplate, which you can optionally read about here.

Libraries

Here are some example libraries that have been bootstrapped with create-react-library.

Want to see a more completed list? Check out Made with CRL.

Want to add yours to the list? Submit an PR at the Made with CRL repository.

License

MIT Β© Travis Fischer

Support my OSS work by following me on twitter twitter

create-react-library's People

Contributors

alanpcs avatar antondelorme avatar baldm0mma avatar bmuenzenmeyer avatar chrisvxd avatar danielsogl avatar dddddanica avatar dependabot[bot] avatar dylanklohr avatar ekoeryanto avatar garryguzy avatar gventuri avatar hurricaneinteractive avatar izayl avatar jasonheylon avatar mattfwood avatar monsterooo avatar nsisodiya avatar psyycker avatar pyrax avatar thclark avatar transitive-bullshit avatar wuweiweiwu avatar zachwolf avatar zyszys avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

create-react-library's Issues

Can't run tests with peer dependencies

My component depends on date-fns as peer dependency and runs fine in the example page that has it installed. However the test doesn't run with the error Cannot find module 'date-fns' from 'MyComponent.js'.

CSS Modules issue

I think there might be an issue somewhere between the CRL/Rollup and the CRA/Webpack implementations of CSS modules but I'm struggling to pin it down.

Full code/examples can be found here.

It appears that CRA only supports import './SomeFile.css'; and CRL only supports import styles from './SomeFile.css';.

screenshot from 2018-05-21 13-02-23
screenshot from 2018-05-21 13-02-39
Live example here

From the below injected CSS it appears as though CRL should support both methods but in the rendered HTML, the className for method 1 is not being renamed: <div class="margin-top-24-lib1"></div>.

CRA fails on method 2 in a similar fashion by still injecting the CSS but completely removes the className when rendered: <div></div>.

The extracted/injected into header CSS looks like this:

<style type="text/css">.CRL1_margin-top-24-lib1__i-ZHE {
  margin-top: 24px;
}
</style>
<style type="text/css">.CRL2_margin-top-24-lib2__22e3M {
  margin-top: 24px;
}
</style>
<style type="text/css">.margin-top-24-app1 {
  margin-top: 24px;
}
</style>
<style type="text/css">.margin-top-24-app2 {
  margin-top: 24px;
}
</style>

We came across this issue when trying to use react-styleguidist. It takes our CRL src components but then uses CRAs Webpack config to build the documentation. This means in the docs our CRL Method 1 now works but CRL Method 2 does not:

screenshot from 2018-05-21 13-32-14

Add more template options?

Some ideas:

  • webpack vs rollup
  • flow or typescript support
  • prettier integration
    ...

I'd really like to keep the default template as minimal as possible, but people should be able to easily swap out different options if they want. Thoughts / suggestions?

Tree shaking not applying for css with modules enabled

Not sure if it's a postcss or rollup config issue, but it seems that enabling modules for postcss makes our bundle export all css.
Consider this in my index.js

export Badge from './js/components/atom/Badge';
export Text from './js/components/atom/Text';

In the example, if I do this:

import { Text } from 'my-lib;
export default class App extends React.Component {
  render() {
    return (
      <Text>Hello</Text>
    );
  }
}

All css from Text and Badge are imported, if though only Text is being used:

image

The JS tree shakes ok, this is happening only to css.

Error while executing the npm install and npm link task

The final step - running npm install and npm link is failing.

I'll look into this time permitting, but wanted to log it here.

βœ– Running npm install and npm link
{ Error: Command failed: /bin/sh -c npm


Usage: npm <command>

where <command> is one of:
    access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
    explore, get, help, help-search, i, init, install,
    install-test, it, link, list, ln, login, logout, ls,
    outdated, owner, pack, ping, prefix, prune, publish, rb,
    rebuild, repo, restart, root, run, run-script, s, se,
    search, set, shrinkwrap, star, stars, start, stop, t, team,
    test, tst, un, uninstall, unpublish, unstar, up, update, v,
    version, view, whoami

npm <command> -h     quick help on <command>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    /Users/scottsilvi/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

[email protected] /Users/scottsilvi/.nvm/versions/node/v8.5.0/lib/node_modules/npm

    at makeError (/Users/scottsilvi/.nvm/versions/node/v8.5.0/lib/node_modules/react-modern-library-cli/node_modules/execa/index.js:169:9)
    at Promise.all.then.arr (/Users/scottsilvi/.nvm/versions/node/v8.5.0/lib/node_modules/react-modern-library-cli/node_modules/execa/index.js:274:16)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:228:7)
  code: 1,
  stdout: '\nUsage: npm <command>\n\nwhere <command> is one of:\n    access, adduser, bin, bugs, c, cache, completion, config,\n    ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,\n explore, get, help, help-search, i, init, install,\n    install-test, it, link, list, ln, login, logout, ls,\n    outdated, owner, pack, ping, prefix, prune, publish, rb,\n    rebuild, repo, restart, root, run, run-script, s, se,\n    search, set, shrinkwrap, star, stars, start, stop, t, team,\n    test, tst, un, uninstall, unpublish, unstar, up, update, v,\n    version, view, whoami\n\nnpm <command> -h     quick help on <command>\nnpm -l           display full usage info\nnpm help <term>  search for help on <term>\nnpm help npm     involved overview\n\nSpecify configs in the ini-formatted file:\n    /Users/scottsilvi/.npmrc\nor on the command line via: npm <command> --key value\nConfig info can be viewed via: npm help config\n\[email protected] /Users/scottsilvi/.nvm/versions/node/v8.5.0/lib/node_modules/npm\n',
  stderr: '',
  failed: true,
  signal: null,
  cmd: '/bin/sh -c npm',
  timedOut: false,
  killed: false }

Poll: convert to single dependency and ability to eject?

One of the nicest things about CRA is that most of the functionality is bundled into a single dependency, react-scripts which makes updating your CRA apps with bugfixes and transitive dependency updates relatively simple.

Currently, create-react-library doesn't perform this type of bundling and instead opts to generate the full boilerplate each time you create a new library. This is already a huge time-saver, but it could possibly be better.

Generating the full boilerplate has the advantage of being simple and leaving more customization power in the hands of the library author. It has the disadvantage that long-term library updates and maintenance will be harder, especially if you're publishing a lot of react libraries. This is something that I've run into myself over the past few months.

The workaround would be to follow suit with CRA and bundle all of the dependencies for create-react-library templates into a single dependency, react-library-scripts, which would allow library authors to update their libraries more easily. This would also necessitate the ability to eject from react-library-scripts in an analogous fashion to how CRA works.

I think there are definitely pros and cons to both, but I wanted to put it out there and see what people think. Not expecting too many responses, but if you feel strongly for one approach or the other, please vote here and respond below.

Thanks!


Jest testing with css modules

Hi. First, awesome package - helps a lot creating libraries.
Now, I'm having issues with test with jest + css modules. Not sure if it's something with rollup or not, but all elements inside the test comes with empty classes. A simple example:

import React from 'react';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Badge from '../Badge';
configure({ adapter: new Adapter() });

...

it('has class for primary color', () => {
  const wrapper = shallow(<Badge primary />);
  console.log(wrapper.debug());
});

Shows me:

<span className="" />

Tried making a few changes on Jest and rollup but with no success. Any clues?

Question: How to use img files other than svg.

It might not be "create-react-library" specific question...

but I am trying to use png or jpg images in my component but I just cant find a way to do it
😭

Appreciate your help.

Add to CRL readme list

Nice work with this library.
Had the pleasure of bootstrapping a login-modal with this, and it definitely made my life easier!

I'd be cool to have this added to the crl readme list 😁

Help: It looks like your Babel configuration specifies a module transformer. Please disable it

Hi,

I'm using the default configuration and one of my modules trigger this error and I can't figure it out.

This module is causing the issue:

import dispatchStdEvent from "vr-ui/web_modules/utils/dispatch-std-event"

And here is the core of the module:

export default function dispatchStdEvent(stdEventName, bubbles, cancelable, element) {
  var newStdEvent
  if (bubbles === undefined || bubbles === null) {
    bubbles = true
  }
  if (cancelable === undefined || cancelable === null) {
    cancelable = true
  }
  try {
    newStdEvent = new Event(stdEventName, {"bubbles": bubbles, "cancelable": cancelable})
  }
  catch (e) {
    newStdEvent = document.createEvent("Event");
    newStdEvent.initEvent(stdEventName, bubbles, cancelable);
  }
  (element || window).dispatchEvent(newStdEvent)
}

This error occurs sometimes but the link given in the error doesn't give enough details since I'm using your default configuration I'm just lost, seems like it doesn't like the package for any reason (I can't find which one).

I got this issue few times with others modules and it was mainly because the export wasn't set to "default" or some strange things my mates did (ES8 requiring an extra module). But here, this one is so simple I have no ideas.

If I copy the whole content of my file "dispatchStdEvent" inside my package, it builds.

The problem comes only from import/export then?

Thanks

simplify predeploy script

I think it is better to run the script without cd-ing
example:
"predeploy": "yarn --cwd example && yarn --cwd example run build",
or

"predeploy": "npm --prefix example install && npm --prefix example run build",

Flow

How to release module with flow support?

Error on running example with yarn

Just created the app, then followed CLI instruction.

In one shell entered the new project the run yarn start (ok)

In the other shell entered /example and run yarn start but I get this:

$ yarn start
yarn run v1.6.0
$ react-scripts start
/bin/sh: react-scripts: command not found
error Command failed with exit code 127.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

"Your module has been created at undefined."

nice lib so far! just trying it out and this is the output:

create-react-library

? Package Name react-wired
? Package Description react wired
? Author's GitHub Handle sw-yx
? GitHub Repo Path https://github.com/sw-yx/react-wired.git
? License MIT
? Package Manager npm
βœ” Copying template to /Users/swyx/OpenSource/react-wired
βœ” Running npm install and npm link
βœ” Initializing git repo


Your module has been created at undefined.

To get started, in one tab, run:
$ cd react-wired && npm start

And in another tab, run the create-react-app devserver:
$ cd react-wired/example && npm start



Because you're using npm, you'll need to publish a dummy version of react-wired first before you can "npm link" your package into the example app.

this is probably an easy fix: "Your module has been created at undefined."

src/ files changed, but can not live-reload

I have seen "anytime you make a change to your library in src/ or to the example app's example/src, create-react-app will live-reload" this words in readme. But It can not live-reload, when I run npm start in src/.

FAQ

How can I use SASS / Less / etc styles in my library?

This is pretty straightforward -- see #56.

Why do you use rollup over webpack?

This is definitely an area of contention, but at the end of the day rollup is much simpler and focused on bundling libraries well whereas webpack tries to do everything and lacks some of the more advanced features of Rollup. For a deeper explanation, I recommend reading Rich Harris’ article Webpack and Rollup: the same but different. In short, a large portion of the community now favors using Rollup for libraries and Webpack for apps.

How can I export multiple components from my library?

Here is a branch which demonstrates how to use multiple named exports. The module in this branch exports two components, Foo and Bar, and shows how to use them from the example app.

What's the preferred way to initialize a React library within a monorepo?

You can use the create-react-library CLI normally within a monorepo to create a package that contains your React component(s). It's up to you whether you create one package that exports N components or N packages that each export one component. create-react-library plays well with Lerna and friends. ✌️

How can I use TypeScript in my library?

Just select the TypeScript template during library initialization via the CLI. Much thanks to @kaltsimon for his work here!

How can I use Flow in my library?

create-react-library doesn't currently have a built-in Flow template. PRs welcome!


Please add any other questions you'd like to see included below. Thanks!

Nothing happens after create-react-library

Hello,

I've installed the package and then executed create-react-library but the command just exits without any message. No prompts, no errors. I've tried that on Ubuntu 16.04 with node version 6.9.5. Any help would be greatly appreciated.

Issue using create-react-library on node 9.2.11 (nvm)

I'm on a MacOS machine High Sierra.
I've installed a new nvm env with node 9.11.2, then just installed globally create-react-library and yarn.

However I'm not able to run the executable:

$ create-react-library
internal/modules/cjs/loader.js:550
    throw err;
    ^

Error: Cannot find module 'isexe'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
    at Function.Module._load (internal/modules/cjs/loader.js:475:25)
    at Module.require (internal/modules/cjs/loader.js:598:17)
    at require (internal/modules/cjs/helpers.js:11:18)
    at Object.<anonymous> (/Users/keul/.nvm/versions/node/v9.11.2/lib/node_modules/create-react-library/node_modules/which/which.js:10:13)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)

eslint error

I have this error in Atom while editing index.js: Cannot find module 'eslint-config-standard-react'.

Question about deploying

Hello,

First of all, thank you for your work, your library is perfectly what I needed !
I have only one problem when I try to run npm run deploy to see the page on github pages, I have a weird error saying :

git-upload-pack '.': git-upload-pack: command not found
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Do you know why I have this error ? I could do all the other stuff (npm publish, work in local, etc...)

I am on Windows if it can help

Getting an error in the example project

npm ERR! path /Users/steven/Development/react-components/example/node_modules/.staging/react-components-b0ed9029/node_modules/@babel/code-frame

This happens when I try to run npm i in the example project.

Any idea what might be causing this?

Tests runs only once instead of watch mode

As the title says. Just tried with a clean copy to make sure I hadn't messed with anything. I guess the expected behavior was that the tests would run continuously? If not I'd appreciate hints on how to achieve that since I don't quite get what the CI=1 means in the test command.

add support for prettier with eslint

Is there any way to configure prettier to be part of the development or build process of create-react-library ?

When maintaining a library it's often get frustrating when your code style get mixed patterns, especially when you need to merge PR's.
prettier and prettier-eslint can greatly help with this issue.
You can configure it to --fix on save or before deploy etc.. thus ensuring that your code style stays consistent no matter what.

How to import css from lib?

I'm trying to import a css file from the lib into the example page but couldn't figure it out and I was also faced with a weird cli behavior.

Whenever I use a path that was invalid, the terminal got stuck into Compiling... and opening the Activity Monitor the node process was over 100% cpu somehow. This only happens when trying to import via import 'my-component/styles.css'. Importing the component itself via import MyComponent from 'my-component' works fine and importing other css files from the same dir as the example also work fine. Oh and if I try to import some other non existent file from the example dir it doesn't cause the cli to get stuck.

npm publish dummy - needed?

I do not understand the following:

Because you're using npm, you'll need to publish a dummy version of ${lib.name} first before you can "npm link" your package into the example app.

I created a new directory (test-it) with create-react-library using npm as the Package Manager.

In the test-it directory I ran

npm start

Then in the example directory I ran

npm link test-it
npm install
npm start

I did not have to publish anything.

Am I missing something?

Note your instructions in the terminal at the end of create-react-library do not mention the need to
run npm install in the example directory. Until I did this I had problems. Peer dependencies may be needed to be installed in the example directory also to get things to work.

Webpack flavor

Your project is really interesting and quite complete. The only reason that stops me from using it within our team is the use of Rollup instead of Webpack. I am not arguing which one is better I am just saying that a Webpack flavor would be an interesting add-on.

Thank you.

Doesnt work well with styled components

I have searched online for many different configs for making this compatible with styled-components and eventually, my terminal starts crashing. I am not a pro so it could be something really simple so this is more of seeking help that an issue.

this is too awesome

this is very awesome!

only weird thing is it took much longer for me to do yarn install and yarn link than npm install and npm link which is very weird.

i am making all new libraries with this thing. no complaints yet!

add unit tests and CI integration

  • run the CLI to create a sandbox module
  • different permutations of options
  • test that the resulting sandbox module builds and passes tests

Thank you :)

Thank you for this package :)
I was able to create my first react reusable component with this package.
https://github.com/ahmednooor/touchflip-react

Also some feedback.
Everything worked great the first time.
But the second time after updating my code, npm run deploy didn't work.
Ultimately I reinstalled the gh-pages globally which resolved the issue.
Hope this helps.

Once again Thank You :)

CLI doesn't work with scoped package

If I'm creating a scoped package (e.g. @my-awesome-org/dope-module) the folder structure created is:

my-awesome-org/
  dope-module

Instead, this should be:

dope-module/

FWIW the name field in package.json works for this.

Error running create-react-library

This is what I'm seeing:

$ create-react-library
/usr/lib/node_modules/create-react-library/index.js:10
module.exports = async () => {
                       ^
SyntaxError: Unexpected token (
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.