JS: Using import/export VS require (file)

In JavaScript there is 2 ways of importing a file from another file.

  • import /export is ES6 syntax and not every browser support yet. Using Babel to transpile javascript is actually using CommonJS which NodeJS use.
Example1:
import "myfile.js"; 
// include the file as is

Example2:
file1.js
export default function(){
 return 1
}
file2.js
import func from "file1.js"
var x = func();

Example3:
file1.js
var func1 = ()=> { return 1; };
var func2 = ()=> { return 0; };
export func1;
export func2;
file2.js
import {func1} from "file1.js";
import {func2} from "file1.js";
  • require(file) is mostly used in CommonJS and Node.JS
Example1:
file1.js
module.exports = {
   x: 0, func1: ()=> 1
}
file2.js
var obj = require("file1.js");
console.log ( obj.x); // return 0

When you are using NodeJS you are more likely to use “require” but in other situation like React. It is most likely ES6 import and export.

Here below is  nice quick cheat sheet I found on the net.

https://hackernoon.com/import-export-default-require-commandjs-javascript-nodejs-es6-vs-cheatsheet-different-tutorial-example-5a321738b50f

Leave a Reply

Your email address will not be published. Required fields are marked *