Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 创建JS库以在npm中工作_Javascript_Node.js_Npm_Module - Fatal编程技术网

Javascript 创建JS库以在npm中工作

Javascript 创建JS库以在npm中工作,javascript,node.js,npm,module,Javascript,Node.js,Npm,Module,我创建了一个带有常用函数的简单JS库: !!window.JsUtils || (window.JsUtils = {}); JsUtils = (function () { "use strict"; return { randomHex: function (len) { var maxlen = 8; var min = Math.pow(16, Math.min(len, maxlen) - 1);

我创建了一个带有常用函数的简单JS库:

!!window.JsUtils || (window.JsUtils = {});

JsUtils = (function () {
    "use strict";
    return {
        randomHex: function (len) {
            var maxlen = 8;
            var min = Math.pow(16, Math.min(len, maxlen) - 1);
            var max = Math.pow(16, Math.min(len, maxlen)) - 1;
            var n = Math.floor(Math.random() * (max - min + 1)) + min;
            var r = n.toString(16);
            while (r.length < len) {
                r = r + randHex(len - maxlen);
            }
            return r;
        },
        ...
    };
}());
填写问题…您就有了一个package.json,如下所示:

{
  "name": "js-utils",
  "version": "0.2.0",
  "description": "Some common used JS functions",
  "main": "js-utils.js",
  "directories": {
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/tonysamperi/js-utils.git"
  },
  "keywords": [
    "js",
    "utils",
    "library",
    "utility",
    "utilities",
    "javascript"
  ],
  "author": "Tony Samperi <github@tonysamperi.it> (tonysamperi.github.io)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/tonysamperi/js-utils/issues"
  },
  "homepage": "https://github.com/tonysamperi/js-utils#readme"
}

但是..这在npm中有效吗?

如果要在节点中使用主文件,只需在主文件中添加导出即可。就这样

module.exports = {
  randomHex(len) {
    var maxlen = 8;
    var min = Math.pow(16, Math.min(len, maxlen) - 1);
    var max = Math.pow(16, Math.min(len, maxlen)) - 1;
    var n = Math.floor(Math.random() * (max - min + 1)) + min;
    var r = n.toString(16);
    while (r.length < len) {
      r = r + randHex(len - maxlen);
    }
    return r;
  },
}

这就是解决办法。我就要发表了,所以…我们看看它是否有效。。 目前,在客户端,一切正常

我还能够确定您是在客户端还是服务器端

(function (exports) {

    function isClient() {
        return typeof window !== "undefined" && !!window.document;
    }

    var clientJsUtils = (function () {
        return {
            htmlCountDown: function (duration, updateFreq, targetEl) {
                var counter = JsUtils.roundNumber(duration, 1000) / 1000;
                var interval;
                var print = function () {
                    counter -= updateFreq / 1000;
                    counter < 0 && (counter = 0);
                    targetEl.innerHTML = counter.toFixed(2);
                };
                interval = setInterval(function () {
                    print();
                }, updateFreq);
                setTimeout(function () {
                    clearInterval(interval);
                    print();
                }, duration);
            },
            jQueryLoad: function () {
                var jq = document.createElement('script');
                jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js";
                jq.onload = function () {
                    console.info("jQuery loaded.");
                };
                jq.onerror = function () {
                    console.info("jQuery not loaded.");
                };
                document.getElementsByTagName('head')[0].appendChild(jq);
            },
            logWithStyle: function (title, msg, style) {
                console.group(title || "");
                console.log("%c" + msg, style);
                console.groupEnd();
            }
        };
    }());

    var JsUtils = (function () {
        hybridJsUtils = {
            randomHex: function randomHex(len) {
                var maxlen = 8;
                var min = Math.pow(16, Math.min(len, maxlen) - 1);
                var max = Math.pow(16, Math.min(len, maxlen)) - 1;
                var n = Math.floor(Math.random() * (max - min + 1)) + min;
                var r = n.toString(16);
                while (r.length < len) {
                    r = r + randomHex(len - maxlen);
                }
                return r;
            },
            randomInt: function (min, max, excludeMin, excludeMax) {
                if (!min || isNaN(min)) {
                    min = 0;
                }
                if (!max || isNaN(max)) {
                    max = 1;
                }
                excludeMax = excludeMax == "true"; //forces to have true or "true"
                excludeMin = excludeMin == "true"; //forces to have true or "true"
                var result = 0;
                if (excludeMax) {
                    result = Math.random() * (max - min) + min;
                }
                else {
                    result = Math.floor(Math.random() * (max - min + 1)) + min;
                }
                return excludeMin ? result : ++result;
            },
            removeTrailingSlash: function (target) {
                return target.replace(/\/$/, "");
            },
            roundNumber: function (value, closest) {
                //cleanup
                if (typeof value === typeof "") {
                    value = value.replace(/[^\d\.\-\ ]/g, "");
                }
                if (isNaN(value *= 1)) {
                    return 0;
                }
                if (typeof closest !== typeof 0 || closest < 1) {
                    closest = 1;
                }
                return Math.round(value / closest) * closest;
            }
        };

        return isClient() ? Object.assign(hybridJsUtils, clientJsUtils) : hybridJsUtils;
    }());

    Object.assign(exports, JsUtils);

})(typeof exports === "undefined" ? this["JsUtils"] = {} : exports);

但您想在节点中使用它吗?因为节点没有窗口对象是的,我也想在节点中使用它,比如lodash!好的,那么第1步:删除窗口引用…理论上,如果我没弄错的话,你可以将任何东西发布到NPM。您只需要更改@MaciejKozieja已经指出的内容,如果目标是对两者使用相同的脚本,您可以通过使用窗口、模块等条件进行更改好的,很好。感谢@JonathanLonowski,链接的答案非常有用。卢卡·塞伊·意大利人?:好的,谢谢,但是这种方式在客户端不起作用,对吗?如果你创建了fancy loader,它可能会起作用,但问题是它将安装到node_modules dir,你必须将其公开,我认为这是不好的,但是,除非你使用一些本机浏览器对象或节点模块,否则你应该很好。它应该是像lodash一样的东西…所以我不应该使用像文件一样的东西。。。如果它转到节点模块…没问题…我只是想,如果我下载到它在客户端工作的任何文件夹…这里,我为您创建了加载程序。不幸的是,它必须使用同步模块加载,但它的工作原理与节点中的一样。
module.exports.randomHex = function(len) {
    var maxlen = 8;
    var min = Math.pow(16, Math.min(len, maxlen) - 1);
    var max = Math.pow(16, Math.min(len, maxlen)) - 1;
    var n = Math.floor(Math.random() * (max - min + 1)) + min;
    var r = n.toString(16);
    while (r.length < len) {
      r = r + randHex(len - maxlen);
    }
    return r;
  },
!function () {
    class Module { constructor(exports) { Object.assign(this, exports) } }
    const modules = {}
    const fetchSync = (file) => {
      var xhr = new XMLHttpRequest()
      xhr.open("GET", file, false)
      xhr.send(null)
      return xhr.responseText
    }

    window.require = (file) => {
      file = file.replace('.js', '').replace(/^\.\//, '')
      const name = `${file}.js`.match(/\/?(.*)\.js/)[1]
      if (modules[file]) return modules[file].exports
      const module_code = fetchSync(`${file}.js`)
      let exports = { exports: {} }
      Function('module', 'require', module_code)(exports, require)

      const module = modules[file] = new Module(exports.exports)
      return window[name] = module
    }
  }()
(function (exports) {

    function isClient() {
        return typeof window !== "undefined" && !!window.document;
    }

    var clientJsUtils = (function () {
        return {
            htmlCountDown: function (duration, updateFreq, targetEl) {
                var counter = JsUtils.roundNumber(duration, 1000) / 1000;
                var interval;
                var print = function () {
                    counter -= updateFreq / 1000;
                    counter < 0 && (counter = 0);
                    targetEl.innerHTML = counter.toFixed(2);
                };
                interval = setInterval(function () {
                    print();
                }, updateFreq);
                setTimeout(function () {
                    clearInterval(interval);
                    print();
                }, duration);
            },
            jQueryLoad: function () {
                var jq = document.createElement('script');
                jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js";
                jq.onload = function () {
                    console.info("jQuery loaded.");
                };
                jq.onerror = function () {
                    console.info("jQuery not loaded.");
                };
                document.getElementsByTagName('head')[0].appendChild(jq);
            },
            logWithStyle: function (title, msg, style) {
                console.group(title || "");
                console.log("%c" + msg, style);
                console.groupEnd();
            }
        };
    }());

    var JsUtils = (function () {
        hybridJsUtils = {
            randomHex: function randomHex(len) {
                var maxlen = 8;
                var min = Math.pow(16, Math.min(len, maxlen) - 1);
                var max = Math.pow(16, Math.min(len, maxlen)) - 1;
                var n = Math.floor(Math.random() * (max - min + 1)) + min;
                var r = n.toString(16);
                while (r.length < len) {
                    r = r + randomHex(len - maxlen);
                }
                return r;
            },
            randomInt: function (min, max, excludeMin, excludeMax) {
                if (!min || isNaN(min)) {
                    min = 0;
                }
                if (!max || isNaN(max)) {
                    max = 1;
                }
                excludeMax = excludeMax == "true"; //forces to have true or "true"
                excludeMin = excludeMin == "true"; //forces to have true or "true"
                var result = 0;
                if (excludeMax) {
                    result = Math.random() * (max - min) + min;
                }
                else {
                    result = Math.floor(Math.random() * (max - min + 1)) + min;
                }
                return excludeMin ? result : ++result;
            },
            removeTrailingSlash: function (target) {
                return target.replace(/\/$/, "");
            },
            roundNumber: function (value, closest) {
                //cleanup
                if (typeof value === typeof "") {
                    value = value.replace(/[^\d\.\-\ ]/g, "");
                }
                if (isNaN(value *= 1)) {
                    return 0;
                }
                if (typeof closest !== typeof 0 || closest < 1) {
                    closest = 1;
                }
                return Math.round(value / closest) * closest;
            }
        };

        return isClient() ? Object.assign(hybridJsUtils, clientJsUtils) : hybridJsUtils;
    }());

    Object.assign(exports, JsUtils);

})(typeof exports === "undefined" ? this["JsUtils"] = {} : exports);
npm install hybrid-js-utils