import vs require in Javascript

실리콘·2023년 2월 20일
0

Some history

Javascript language specification is standardized, by ECMAScript specification.
the ES in ES6 is short for ECMAScript

In ES6, which is the current standard for javascript, using import is the standard.

However, in nodeJS, we often see require to use modules. This is because before ES6 standard, nodeJS introduced CommonJS as its standard, and this used require to use modules.

Comparison

So currently, it is recommended to use import.
Some of its advantages are

  • The ES6 standard
  • import is determined at compile time, asynchronously. so enables:
    • Support for static analysis -> debuggin
    • tree shaking -> removed unused code
    • dynamic code loading. uses Promise to resolve module imports
  • can import only needed part of module.

But we still need to konw require
as it

  • still legacy code base uses this.
  • enables dynamic loading of modules at runtime.

Miscellaneous

I hear it is pain to create a js module that can handle both import and require.

profile
software engineer

0개의 댓글