How to Import a JavaScript File into Another JavaScript File
Take Advantage of a Keyword, New as of ES2015
Before ES2015, JavaScript had no built-in way of importing a script into another script. With the introduction of modules in ES2015 you can use the import
keyword to include other scripts like this:
<script type="module">
import { fn } from './test.js';
fn('meow');
</script>
This code imports the fn
function from test.js
. In the script that’s being imported (in this case test.js
), you should specify the function (or variable) to be exported by using the export
keyword:
export function fn(text) {
const div = document.createElement('div');
div.textContent = `${text}`;
document.body.appendChild(div);
}
You can also import a script on demand. Dynamic import()
allows you to import a script when needed. Here’s an example:
<script type="module">
const element = document.getElementById('myBtn');
element.addEventListener('click', e => {
e.preventDefault();
import('test.js').then(module => {
module.fn('meow');
});
});
</script>
The ability to import code from other scripts allows you to create modular applications, which provides benefits like code reuse, reduced development time, and easier debugging.
If you enjoyed this article, you may also like Faraz Kelhini’s book, Modern Asynchronous JavaScript. Through October 1, 2022, you can use promo code fkajs_medium_35 to save 35% on the ebook version. Promo codes are not valid on prior purchases.