![](/img/trans.png)
[英]How do you organize js files so that you can require from them within one npm package?
[英]How do you use an npm package with require & module export as a plain JS library
我不確定我什至在這里問了正確的問題,抱歉,但我認為兩個一般問題是:
require
等修改 node.js package 以用作 HTML 中的普通嵌入式腳本/庫?我正在嘗試在沒有節點或構建系統的環境中使用這個小型 JS 庫NoSwearingPlease (這是一個 npm 包)——所以我只是想像 jQuery 或在HTML,然后用一個小的內聯腳本來使用它。
我可以看到要使其正常工作需要做幾件事:
我嘗試使用 jQuery getJSON 但我只是不明白 class 和 scope 位足以使用它我認為:
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);
});
請停下來。 謝謝!
無需修改,當在節點之外 class 只是附加到window
(全局):
fetch("https://cdn.jsdelivr.net/gh/ThreeLetters/NoSwearingPlease@master/swears.json").then(response => { return response.json(); }).then(data => { var noSwearing = new NoSwearing(data); console.log(noSwearing.check("squarehead")); });
<script src="https://cdn.jsdelivr.net/gh/ThreeLetters/NoSwearingPlease@master/index.js"></script>
以后,您可以通過查看源代碼並查找您不理解的內容來自行回答此類問題。 話雖這么說,這就是我自己收集到的東西。
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 the window
or has a UMD export (which in this case, it does). 如果是這樣,您可以下載源代碼或使用 JSDelivr 之類的 CDN 並添加<script>
標簽來鏈接它。
<script src="https://cdn.jsdelivr.net/gh/ThreeLetters/NoSwearingPlease@master/index.js"></script>
我很難破譯你的腳本(據我所知,它有一些語法錯誤),所以如果你有一個包含 JSON 和你需要檢查的字符串str
的變量ns
,你可以這樣做:
var checker = new NoSwearing(ns);
checker.check(str);
順便說一句,您應該真正使用構建工具來優化您的包大小並使使用包變得更容易。 並考慮為document.querySelector
、 fetch
/ XMLHttpRequest
和其他現代 JavaScript API 刪除 jQuery。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.