简体   繁体   中英

How do I get a js library without import

I want to make a js library, and I have all the code. Libraries like Jquery can let you do like

<script src = "..."></script>
<script>
//uses the library
</script>

without the 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:

 <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM