Tip 47: Isolate Functionality with Import and Export
In this tip, you’ll learn how to share code between files.
Sharing code between files
In the bad old days of JavaScript, you kept all code in a single file. Even worse,
developers would put all their JavaScript code in the DOM under a single <script>
tag.
Things got better slowly. First, someone created code to minify and concatenate files so at least you had only one small import statement. Then projects such as Require.js and CommonJS gave developers a way to share code between files using modules. With the module system, JavaScript developers were finally able to easily reuse code in a project.
Modules have been simplified and are now simple import and export statements. And with this simple interface, not only can you share code between files in a project, but you can also use community code with nearly identical syntax. You’ll see more about community code in the next tip. For now, let’s look at how to import and export code.
Importing and exporting code
This code won’t work out-of-the box. It’s still a good idea to combine and minify your code to a single file. Eventually, browsers will be able to dynamically import code, but for now, you still need to create single files, often called bundles or packages. You’ll see how in Tip 50, Use Build Tools to Combine Components.
You’ve actually been using exported code throughout the course. You wouldn’t know unless you looked at the courses’s source code because the examples hid the code export. Importing and exporting is just that simple. You export any existing code with a single statement.
Example: Exporting a function
Here’s some code from Tip 36, Prevent Context Confusion with Arrow Functions.
Get hands-on with 1200+ tech skills courses.