简体   繁体   English

试图让一个JavaScript文件在node.js文件和浏览器中都可用

[英]Trying to get one JavaScript file to be usable both by a node.js file and in a browser

I've got a relatively simple JavaScript file (call it foo.js) that has 3 functions that are being called by a second JS file in the browser. 我有一个相对简单的JavaScript文件(称为foo.js),其中包含3个功能,这些功能由浏览器中的另一个JS文件调用。 There are a few other functions in foo.js, but they are only used internally. foo.js中还有一些其他函数,但它们仅在内部使用。

Now foo.js also needs to be able to be used by a JS file running in node.js. 现在,foo.js也需要能够由在node.js中运行的JS文件使用。 Same thing, only needs to access the three basic functions. 同样的事情,只需要访问三个基本功能即可。

So I added module.exports around these three functions like so: 因此,我围绕这三个函数添加了module.exports,如下所示:

module.exports = {
    init_foo: function (bar){
        return JSON.parse(bar);
    },
    export_foo: function (foobar){
        return JSON.stringify(foobar);
    },
    switch_foo: function (boofar){
        switch(boofar)
        {
            case 'A':
                return 1;
            case 'B':
                return 2;
            default:
                return 3;
        }
    }
};

So now my node.js file can get the code by using 所以现在我的node.js文件可以通过使用以下代码获取代码

var foo = require('./foo.js');

But of course the browser code can't use it anymore, gives an error. 但是,当然,浏览器代码无法再使用它,这会导致错误。 When looking for a solution I found browserify but I can't seem to get it to work (keeps returning an empty file even when doing the suggested tutorial, guessing it's something to do with the set up of the system I am using, just not sure what), and it seems like it's more complex then I need anyway (don't want to browserify the entire browser JavaScript code, but can't browserify foo.js, have to make a new JS file that requires foo.js and uses it then browserify that, effectively adding a middle man that wasn't needed before). 在寻找解决方案时,我发现browserify却无法正常工作(即使在执行建议的教程时也保持返回一个空文件的方式,猜测这与我正在使用的系统的设置有关,只是没有确定),而且似乎还比我更复杂(不想对整个浏览器的JavaScript代码进行浏览器化,但无法对foo.js进行浏览器化,必须制作一个需要foo.js和使用它,然后将其浏览器化,从而有效地添加以前不需要的中间人)。

Seeing as how the code I want to access with both node.js and from the browser is relatively simple is there an easy way to do this? 看到我想同时通过node.js和从浏览器访问的代码相对简单,是否有一种简便的方法? (Just writing the code twice isn't a solution, it is simple code but I want to only have to edit it once for changes to propagate to both locations). (仅编写两次代码不是解决方案,这是简单的代码,但是我只需要编辑一次就可以将更改传播到两个位置)。

It is probably the best to use a specialized packet like browserify but for a small thing like yours the following might be a better fit. 最好使用特殊的数据包(例如browserify),但对于像您这样的小东西,可能会更适合。 (I used it in my primesieve module) (我在我的primesieve模块中使用了它)

var myModule = (function() {
  return {
    init_foo: function (bar){
      return JSON.parse(bar);
    },
    export_foo: function (foobar){
      return JSON.stringify(foobar);
    },
    switch_foo: function (boofar){
      switch(boofar)
      {
        case 'A':
            return 1;
        case 'B':
            return 2;
        default:
            return 3;
      }
    }
  };
})();

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  module.exports = myModule;
} else {
  if (typeof define === 'function' && define.amd) {
    define([], function() {
        return myModule;
    });
  } else {
    window.myModule = myModule;
  }
}

There have been some time passed since and better methods might have evolved but it is small and simple and worked for me. 从那以后已经过去了一段时间,可能已经开发出了更好的方法,但是它既小又简单,对我有用。

Welp, one thing you can do is only assign a property of 'module' if it exists. 抱歉,您只能做的一件事情就是分配'module'属性(如果存在)。 And hope that no other JavaScript has introduced that to your browser environment as a global variable. 并希望没有其他JavaScript将其作为全局变量引入浏览器环境。

(function() {
  var exports
  ...
  if (this.hasOwnProperty('module'))
    module.exports = exports
})()

Note that the this there is the global object. 注意, this有全局对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM