Browserify import/require?

12,051

require() is the Node module system (CommonJS) in ES5. import is ES6 module syntax.

If you want to browserify modules written with ES6 module syntax you'll need to compile them using something like babelify (or babel by other means).

Share:
12,051

Related videos on Youtube

panthro
Author by

panthro

Updated on June 19, 2022

Comments

  • panthro
    panthro about 2 years

    I'm trying to pick up browserify and have been through a number of examples.

    In one example I see the use of 'import':

    import 'jquery';
    

    and importing local files with:

    import Header from './Header';
    

    but in other examples I see people importing via:

    require('./Header');
    

    What is the difference?

  • Matthias
    Matthias almost 8 years
    Not sure I understand. Why would I need browserify (or require for that matter) if I transpile ES6 via Babel? Doesn't that translate the import statements to something older JS environments understand?
  • JMM
    JMM almost 8 years
    @Matthias pre-ES6 has no native module system, so there are multiple systems constructed in userland code (e.g. CommonJS / Node modules and AMD). require() is part of the Node module API. So that's one of the "something older JS environments understand" targets you can compile to (that will run in Node). However, browsers have no knowledge of those APIs. Node implements it by wrapping modules in a function that injects require() etc. In a browser require() would just be a reference error. Browserify makes it work in the browser, and bundles a whole dependency graph into a single script.
  • Matthias
    Matthias almost 8 years
    Got it. Thanks for clarifying!
  • JMM
    JMM almost 8 years
    @Matthias No problem!
  • joedotnot
    joedotnot over 4 years
    what would be great is if someone posted an example or link on how to use both browserify and babel together.