我不确定在这里甚至没有问正确的问题,对不起,但我认为这两个一般性问题是:
- In what way do you need to modify a node.js package using
require
etc to be used as a plain embedded script/library in HTML? - How do you call a class constructor (?) in JS as a function to validate a form field?
I'm trying to use this small JS library NoSwearingPlease (which is an npm package) in an environment with no node or build system – so I'm just trying to call it like you would jQuery or something with a script & src in the HTML, and then utilise it with a small inline script.
我可以看到要使此工作正常,需要做一些事情:
- JSON文件需要以其他方式调用(不使用require等)
- checker变量需要重写,再次不需要
我尝试使用jQuery getJSON,但我只是不了解该库的类和作用域位,不足以使用它,我认为:
var noswearlist = $.getJSON( "./noswearing-swears.json" );
function() {
console.log( "got swear list from inline script" );
})
.fail(function() {
console.log( "failed to get swear list" );
})
noswearlist.done(function() {
console.log( "done callback as child of noswearlist variable" );
var checker = new NoSwearing(noswearlist);
console.log(checker);
});
请暂停。谢谢!
将来,您可以通过查看源代码并查找不了解的内容来自行回答此类问题。话虽如此,这就是我本人可以做的事情。
For your first question, if you have no build tools you can't use
require
, you have to hope your NPM package supports adding the class to thewindow
or has a UMD export (which in this case, it does). If so, you can download the source code or use a CDN like JSDelivr and add a<script>
tag to link it.I'm having a hard time deciphering your script (it has a few syntax errors as far as I can tell), so here's what you do if you have a variable
ns
containing the JSON and the stringstr
that you need to check:As an aside, you should really use build tools to optimize your bundle size and make using packages a lot easier. And consider dropping jQuery for
document.querySelector
,fetch
/XMLHttpRequest
, and other modern JavaScript APIs.工作正常: