53

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

hippietrail
  • 13,703
  • 15
  • 87
  • 133
crash
  • 3,060
  • 4
  • 22
  • 41

1 Answers1

86

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

LogicalBranch
  • 3,582
  • 2
  • 16
  • 48
CodingIntrigue
  • 65,670
  • 26
  • 159
  • 166
  • 4
    This actually appears to be incorrect according to the [same page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_module_for_its_side_effects_only) that you referenced in your answer. That kind of import will execute code but not keep any references to variables that are defined (I confirmed this behavior in my project as well). – intcreator Mar 30 '18 at 00:37
  • @brandaemon can you show an example of what you mean by “keeping variables”? How are you comparing the two? Native modules vs NodeJS or transpiling with Babel? – CodingIntrigue Mar 30 '18 at 07:38
  • 4
    For example, if I have a file called `code.js` where I have `const foo = 1; console.log(foo);` and I say `import "code.js"` in `main.js`, I will not have access to `foo` inside `main.js`. However, `1` will be printed to the console since the code inside `code.js` will execute. If that's a little hard to follow, here's a [StackBlitz](https://stackblitz.com/edit/js-lanbce?file=index.js) demonstrating what I'm doing. – intcreator Mar 30 '18 at 17:28
  • 3
    @brandaemon That’s exactly how NodeJS & require works. It’s not that it’s not keeping references but those variables are *block scoped* so you cannot access them in the calling module. If you had of put foo on either the window (browser) or global (Node) this would behave as you expect – CodingIntrigue Mar 30 '18 at 17:44
  • 2
    Ah okay. So there is no way to include scoped references without explicit `export`s? I'm thinking of the behavior you get when you have multiple script tags in an HTML file. – intcreator Mar 30 '18 at 17:49
  • 1
    @brandaemon There isn’t, no. I can see how you would think it would work the same way though! – CodingIntrigue Mar 30 '18 at 17:57