How to Import a JavaScript File into Another JavaScript File

Take Advantage of a Keyword, New as of ES2015

Faraz Kelhini
The Pragmatic Programmers
2 min readSep 14, 2022

--

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:

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:

You can also import a script on demand. Dynamic import() allows you to import a script when needed. Here’s an example:

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.

--

--

Faraz Kelhini
The Pragmatic Programmers

Faraz is a professional JavaScript developer who is passionate about promoting patterns and ideas that make web development more productive. Website: eloux.com