1

Based on what I have put together reading here and here, the way to publish a react module to NPM, and then use it in another project while the component itself is in the node_modules director should look like this

  1. write a module, then export it
  2. fill in the main property of package.json with the name of the script, in my case, dist/index.js
  3. npm install it from the project where you want to include it
  4. serve the script statically from server.
    • I have something that looks like this to serve the js file: app.use('public/componentA', express.static(path.join('node_modules', 'componentA'));
    • this is not the totally real code, but it works, I can see the JS in the browser if I load it.
  5. require component

index.js

var React = require('react');
var Component = require('../public/componentA/');
var hook = document.getElementById('hook');
React.render(Component, hook);

However when I try to webpack this I get the error

ERROR in ./lib/index.js Module not found: Error: Cannot resolve directory './public/componentA' in /Users/me/Documents/tests/reactcomponenttest/lib

What here is preventing me from using my module? I am supposing that the public dir is not available anywhere but the specific port. If that's the case how do we use the node use suggestion from my second link?

1

1 Answer 1

1

You have to require the module by it’s name. If you published the module with the name componentA, write something like this: var Component = require('componentA');

Step 4. is not necessary at all. Webpack bundles all your JavaScript files into one file. So if you require(‘componentA') it will basically copy the content of componentA’s dist/index.js into the final bundle.js.

At the end you simply serve the bundle.js .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.