I am getting to know node.js and javascript frontends, and sharing modules/components between frontend and backend (Node.js with express in this case) has become interresting (especially when using React.js). This is not a new question, however I have not been able to find a good method suiting my current needs.
What I want:
Use project modules and submodules both on frontend and Node backend with working paths in the require statements, and the least possible bolierplate code for file/module loading. Hopefully without the need for a build step.
For instance, I have a react component for rendering HTML. This component is used on frontend when the webapp is active, and on backend when pre-generating the html. This is just an example case, the main requirement is as stated above.
Best case example, project module file (not actual tested code):
var React = require('react'),
MyLocalSubmodule = require('path/modulename');
var ThisComponent = React.createClass({
/* ...something.... */
});
module.exports = ThisComponent;
The problems:
Question: Is there any frontend loader that can run unwrapped CommonJS modules without prebuilding them and without any boilerplate or similar hacks in the module file?
Question: Is there a non-hackish good way to require local (project) modules and submodules inside modules with the same name syntax in the require statement (var myModule = require('frontend-backend-shared-syntax');) on both frontend and Node backend?
Last question: What is your best suggested way of making node/frontend sharable project modules (including use of submodules)?
You can use the Browserify API to bundle the JavaScript on demand.
There are several open source projects that let you do this (e.g. https://www.npmjs.org/package/browserify-middleware).
To create modules with browser and node code in one module, you can specify a "browser" property in your package.json file. Browserify will then use the specified file as the entry point in browser code while node will load the file specified in "main".