Last active
February 27, 2021 16:16
-
-
Save darkcris1/dc1d5490ae2436771405ce02e5563bac to your computer and use it in GitHub Desktop.
Install a npm package with udm type only in the browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This will return true if the value is some of the items | |
* @param {string} pkgName | |
* @param {string} functionName | |
* @param {function} callback | |
*/ | |
function npm(pkgName,functionName,callback){ | |
const http = new XMLHttpRequest(); | |
const url = "https://unpkg.com/" + pkgName; | |
const global = window || this; | |
http.open("GET",url); | |
http.send(); | |
http.onreadystatechange = function(res){ | |
if (http.readyState === XMLHttpRequest.DONE) { | |
const status = http.status; | |
switch (status) { | |
case 200: | |
new Function(http.responseText)() | |
const fn = global[functionName]; | |
if (typeof fn !== "function") throw new Error("function name must be valid"); | |
callback(fn); | |
break; | |
case 404: | |
throw new Error("Package Not Found"); | |
default: | |
throw new Error("Network Error"); | |
} | |
} | |
} | |
} | |
// Example | |
npm("sweetalert","swal",(swal)=>{ | |
swal("asdasd") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment