Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 import equivalent of require() without exports

By using require(./filename) I can include and execute the code inside filename without any export defined inside filename itself.

What is the equivalent in ES6 using import ?

Thanks

like image 932
crash Avatar asked Dec 16 '16 08:12

crash


People also ask

Can I use import instead of require?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .

What is difference between import and require?

The major difference between require and import , is that require will automatically scan node_modules to find modules, but import , which comes from ES6, won't. Most people use babel to compile import and export , which makes import act the same as require . The future version of Node.

What is require () in JavaScript?

The require() method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node. js application, you can simply use the require() method. Example: var yourModule = require( "your_module_name" ); //.js file extension is optional.


1 Answers

The equivalent is simply:

import "./filename"; 

Here are some of the possible syntax variations:

import defaultMember from "module-name";    import * as name from "module-name";    import { member } from "module-name";    import { member as alias } from "module-name";    import { member1 , member2 } from "module-name";    import { member1 , member2 as alias2 , [...] } from "module-name";    import defaultMember, { member [ , [...] ] } from "module-name";    import defaultMember, * as name from "module-name";    import "module-name"; 

SOURCE: MDN

like image 172
CodingIntrigue Avatar answered Sep 28 '22 23:09

CodingIntrigue