JavaScript Import vs Require

Sep 24, 2020

import is part of JavaScript/ES6, while require is part of Node.js.

  • Node.js: require(), module.exports and exports
  • JavaScript: import, export

require will scan node_modules to find modules, but import won't. But if you are using babel, import and require are pretty much the same.

require can be used for importing conditionally. For example, Nuxt support both server/static side and client side (Browser), and fs module is only available on server/static side in Node.js environment.

if (process.static || process.server) {  const fs = require('fs')}

I guess import dynamic module would work as well

if (process.static || process.server) {  import('fs')    .then((fs) => {    })  // or  let fs = await import('fs')}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.