我创建了一个具有常用功能的简单 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;
},
...
};
}());
我希望能够通过 NPM 安装它,这样每当我更新核心时我就可以在我的项目中更新它。 但我找不到关于如何做到这一点的线性指南..
到目前为止我只知道你必须初始化一个 npm 项目
npm init
填写问题......你就有了一个像这样的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 中可行吗?
最佳答案
如果你想在 Node 中使用它,你只需要在主文件中添加导出。就像这样
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;
},
}
或者像这样
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;
},
然后只需运行npmpublish
,你的包就会公开可用
浏览器加载器:
!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
}
}()
关于javascript - 创建 JS 库以在 npm 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008675/