[英]How do I get a js library without import
I want to make a js library, and I have all the code.我想做一个js库,我有所有的代码。 Libraries like Jquery can let you do like
像 Jquery 这样的库可以让你喜欢
<script src = "..."></script>
<script>
//uses the library
</script>
without the import * from JQuery
.没有
import * from JQuery
。 How can I do this without declaring the library a modular or importing?如何在不将库声明为模块化或导入的情况下做到这一点?
Assign the top-level object to a property on window
, just like jQuery does:将顶级 object 分配给 window 上的属性,就像
window
一样:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> // testing jQuery: console.log(window.$); console.log(window.jQuery); console.log($); // same as window.$ console.log(window.jQuery === $); </script> <script> // your module (imagine this was hosted and loaded via the "src" attribute like jQuery) const myMath = {}; myMath.add = (...numbers) => numbers.reduce((sum, n) => sum + n, 0); window.MY_MATH = myMath; </script> <script> // use myMath const {add} = window.MY_MATH; console.log(add(1, 2, 3, 4)); // 10 </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.