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.
// library.js
const hello = 'Hello World!'
// main.js
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.
// library.js
function libraryName () {
// All your code here
}
// main.js
// Activates library
const result = libraryName()