Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Importing and Exporting Modules in Node.js

Using import instead of require?

Coming from python i seem to gravitate towards using the import syntax instead of require. This to me makes it more verbose, and you can use the function names directly. Are there any drawbacks/ best practices that make this less desirable than using the require syntax?

import { shortenString, reverseString } from './helpers';

1 Answer

Steven Parker
Steven Parker
231,261 Points

There is more than just a syntactical difference here, these are used for different things. In particular, require() is a function in Node.js, and cannot be used in ordinary (front-end) JavaScript code.

And in Node.js, the way they are evaluated is different. For example, you can use variables with require() but not with import:

require(`${folder}/module.js`).myfunc;          // this will work
import { myfunc } from `${folder}/module.js`;   // but this will not

For more details, see the MDN Guide page for Modules.