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).
Related videos on Youtube
Author by
panthro
Updated on June 19, 2022Comments
-
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 almost 8 yearsNot sure I understand. Why would I need
browserify
(orrequire
for that matter) if I transpile ES6 via Babel? Doesn't that translate theimport
statements to something older JS environments understand? -
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 injectsrequire()
etc. In a browserrequire()
would just be a reference error. Browserify makes it work in the browser, and bundles a whole dependency graph into a single script. -
Matthias almost 8 yearsGot it. Thanks for clarifying!
-
JMM almost 8 years@Matthias No problem!
-
joedotnot over 4 yearswhat would be great is if someone posted an example or link on how to use both browserify and babel together.