import
is part of JavaScript/ES6, while require
is part of Node.js.
- Node.js:
require()
,module.exports
andexports
- 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')}