ES6 import equivalent of require() without exports

60.3k views Asked by At

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

2

There are 2 answers

9
CodingIntrigue On BEST ANSWER

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

0
Empi On

The answer should be changed, this does not work anymore as is. If you still want to use import './otherfile.js' without using exports, just to split your code up for readability you have to add type="module to the import of your js file in the html

<script src="js/main.js" type="module"></script>

Edit: It seems you also have to add the .js (otherfile.js) or it doesn't work anymore either.