Skip to content

Instantly share code, notes, and snippets.

@darkylmnx
Last active March 20, 2019 09:34
Show Gist options
  • Save darkylmnx/6bb41fb556cbbb89cd334f0b2046a4c1 to your computer and use it in GitHub Desktop.
Save darkylmnx/6bb41fb556cbbb89cd334f0b2046a4c1 to your computer and use it in GitHub Desktop.
How do exports and imports work in JS bundlers ? (parcel etc...)
// this is app.js, your entry point in your HTML
import { data } from './data.js'
// we use brackets because we only want to export the "data" key exported
// though it will only contain "data" here, everything will be evaluated and executed in data.js
import './scripts'
// here, everything in scripts.js will be evaluated and executed BUT,
// no variables, constants or functions from scripts.js are accessible from here
// "sum" is not accessible, because "sum" was not exported from scripts.js
console.log('HEY HEY I AM app.js');
console.log(data);
// here we only export data
// the name of the export is "data"
// this exports the array
export var data = [1, 2, 3, 4, 5]
// here we only export a add function
// the name of the export is "add"
// this exports the function
export function add(a, b) {
return a + b
}
// here we only export the string
// the export has no name because it is the default export
// if we need this app.js for example
// we would need to do:
// import TheNameIwant from './data.js'
// "TheNameIwant" is really a random name because
// the export just exports the value as a default value
// it doesn't give a "name" to the value
export default "Ariel the mermaid"
<!DOCTYPE html>
<html>
<head>
<title>hello</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
// i do not export anything
// but i import things
// here "Character" will contain the default value exported in data.js
// while "add" will be the value exported from data.js that has the export name "add"
import Character, { add } from './data.js'
// you can even alias named exports
// import { add as MyAddFunc } from './data.js'
// here "MyAddFunc" contains what "add" contains in data.js, so a function
// in this file, we could use "MyAddFunc" instead of "add"
console.log(Character); // this will show "Ariel the mermaid" in the console
const sum = add(1, 5);
console.log(sum); // this will show 6 in the console because "add" was exported and containing a function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment