问题
I created a simple JS library with common functions:
!!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;
},
...
};
}());
I'd like to be able to install it trhough NPM, so that whenever I update the core I can update it on my projects. But I cannot find a linear guide on how to to this..
Till now I only understood you have to init an npm project
npm init
Fill the questions...and you have a package.json like this:
{
"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"
}
But..would this work in npm?
回答1:
You just have to add exports in main file if you want to use it in node. Just like so
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;
},
}
or like so
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;
},
Then just run npm publish and your package will be publicly avalieble
Browser loader:
!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
}
}()
回答2:
This is the solution. I'm about to publish so...we'll see if it works.. For now ok on the client-side.
I was also able to determine if you are on client-side or server-side.
(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);
This is the current version. (1.0.2)
npm install hybrid-js-utils
来源:https://stackoverflow.com/questions/50008675/create-js-library-to-work-in-npm