Write a module that works both in nodejs and requirejs

前提是你 提交于 2020-01-21 19:34:31

问题


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.



来源:https://stackoverflow.com/questions/23418146/write-a-module-that-works-both-in-nodejs-and-requirejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!