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?
Browserify solves the problems of having too many JS files referenced in your HTML, inability to use Node modules in the browser, and inability to reference your own modules in your own code. Watchify streamlines the process of bundling your files and will make a change every time you change a JS file in your project.
1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
Require is Non-lexical, it stays where they have put the file. Import is lexical, it gets sorted to the top of the file. It can be called at any time and place in the program. It can't be called conditionally, it always run in the beginning of the file.
Hello World With Browserify With Browserify you can write code that uses require in the same way that you would use it in Node. Browserify parses the AST for require() calls to traverse the entire dependency graph of your project. Drop a single <script> tag into your html and you're done!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With