Search code examples
reactjscreate-react-appnpm-publish

How to publish existing CRA application to npm(any) repository?


I have a working application consisting multiple components created using create-react-app, each component is a separate app in itself again created using create-react-app.

All the components are ejected so that I could integrate it together.

Now, I want to publish the components to NPM/Private repository but as per CRA deployment guide, it doesn’t support publishing of CRA based components directly out of the box, it suggests using nwb, but I couldn’t figure out how to use nwb to publish ‘existing’ components.

I have also looked at the one of the medium post where it suggests using the babel-cli to generate the dist/build files but that’s failing for some babel configuration which works well otherwise.(sorry, don’t have link at the moment as I am posting this from cellphone).

Any help is appreciated.


Solution

  • You can do it by using babel-cli npm package which will compile your react application code and then you can publish it using npm publish command, the detailed steps are as follows.

    • Install the babel-cli package in your create-react-app using npm install babel-cli command.

    • Create .babelrc file and add following contents to use "react-app" preset provided by babel.

    {
            "presets": [["react-app"]],
    }
    
    • Add distribute command in package.json using following code, this command compiles the code from src folder to dist folder. Generally, I do not include my test files in published library so the --ignore argument skips the tests files like *spec.js and *test.js, this argument is optional and you can remove --ignore spec.js,test.js if you would like to include test files in your published library. The --source-maps argument includes the source maps for the included source files :
        "distribute": "set NODE_ENV=production&&babel src --out-dir dist --copy-files --ignore spec.js,test.js --source-maps"
    
    • Execute the command npm run distribute which will generate the files in dist folder.
    • Set private: false in package.json to make available for publish
    • Set main file of your distributed package using following command, in my case I directly use App.js
    "main": "dist/App.js"
    
    • Add following code for publishing the package and provide repository related details
    "publishConfig": {
        "registry": ""    
      } 
    
    • You can use npm run publish command to distribute your react app source code as library.