Create node module and <script> in one file

限于喜欢 提交于 2019-12-13 07:00:39

问题


How can I write my source file so that it can be "required" and <script src=""> from one code base?

I have hit a rare function that makes sense on both side of the app and would like to only maintain one version.

Is it possible to make a script be usable on both sides assuming it does not use any platform specific functions?


回答1:


The script itself:

var myFunc = function(){
};

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
  module.exports = myFunc;

Now you can either require() this module or just include it into your web-page with <script type="text/javascript" src="..."></script>




回答2:


Check for module to exist, and if it doesn't, use window instead.

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = factory();
    } else {
        window.myObj = factory();
    }
}(function (){
    // your code here, return what should be exported.
    var myObj = {foo:"Bar"};
    return myObj;
}));

Additionally, if you need to require in additional dependencies, you could change the above to this:

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = factory(require('somemodule'));
    } else {
        window.myObj = factory(window.somemodule);
    }
}(function (somemodule){
    // your code here, return what should be exported.
    var myObj = {foo:somemodule("Bar")};
    return myObj;
}));



回答3:


You can use requirejs on client side too and so to include that module by requirejs() from <script> on your page,



来源:https://stackoverflow.com/questions/31322070/create-node-module-and-script-in-one-file

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