You can include a library with <script> tags. If you choose this approach, make sure you include the library before your main JavaScript file.
<script src="library.js"></script><script src="main.js"></script>Libraries linked this way will have the same global scope as your main JavaScript file. If your library contains global variables, these variables will be accessible inside your main JavaScript file.
const hello = 'Hello World!'console.log(hello)
We donβt want variables to leak into global scope because they can cause naming conflicts with other libraries or with the main JavaScript file.
If you build a library that uses a <script> tag, you want to encapsulate your code so the variables donβt leak into the global scope.
How to encapsulate
There are three ways to encapsulate libraries:
- With a block scope
- With a function
- With an IIFE
If youβre building an Automatic Library, you can encapsulate code with block scopes or IIFE. Your code will be executed once the user includes your library into their project.
// Use block scope{ // All your code here...}
// Or IIFE;(function () { // All your code here...})()If youβre building a Manual Library, you need to encapsulate your code with a function. Users will be able to call your function and assign the returned value (if any) into a variable.
function libraryName() { // All your code here}// Activates libraryconst result = libraryName()Welcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson