Write a module that works both in nodejs and requi

2019-02-28 00:29发布

问题:

I wrote a small parser that currently works in node app, but wondering if there is a way that I can make a module that will work both in NodeJS app and client side app that uses requirejs?

path/to/lib/index.js

function someRandom(strings) {
  // we are doing something here
  return strings
}

exports.someRandom = someRandom;

Right now I'm getting this in client-side

Uncaught ReferenceError: exports is not defined 

I know that I can use node requirejs and then change the structure to use define but is there other way without adding node requirejs?

This is my js/main.js file

require(["path/to/lib/index"], function(something) {
    // will do something here
});

回答1:

The way I prefer to do it is to write all my modules in the AMD syntax (use define) and use amd-loader to load them in Node. Note that this solution is not using RequireJS, even though the AMD syntax is used.

However, there's a way to do it without having to use the AMD syntax. You can use r.js to wrap your Node modules. For instance, if you put your tree of Node modules in in, you can do:

$ r.js -convert in out

This will create in out a tree of files that correspond to those in in but wrapped with the define call. You can then load these in the browser using RequireJS. There are limitations. Some are obvious, like not being able to use the Node modules that depend on the Node runtime (like fs, child_process, etc.). Some are more subtle, like the fact that you can't use require(foo) where foo is a variable (RequireJS will handle only string literals there). See the documentation for the details.