We've seen how to write code in .js
files then use <script src="myfile.js" />
to load them in the HTML.
To avoid having files which grow too large, it's useful to split up your files to keep them to a manageable size.
export default
once per file.export default "Banana"
export default 1
export default [1,2,3]
export default {hello: "world"}
export default (a, b) => a + b
export default (a, b) => { return a + b }
export default const x = 1
You can then import your export default
'd expression in another file:
import hello from './hello'
console.log(hello)
Importing an exported default, you can name the import whatever you like:
import hello123 from './hello'
console.log(hello123) // <--- hello123 is not named like the original.
myFolder/banana.js
:
export default "Banana!"
myFolder/fruitBowl.js
:
import banana from './banana'
console.log(banana)
// prints "Banana!"
myFolder/banana.js
:
export default () => "Banana!"
myFolder/fruitBowl.js
:
import banana from './banana'
console.log(banana())
// prints "Banana!"
myFolder/maths.js
:
export default (a, b) => a + b
myFolder/doSomeMaths.js
:
import adder from './maths'
console.log(adder(1, 2))
// prints 3
myFolder/maths.js
:
export default (a, b) => a + b
myFolder/doSomeMaths.js
:
import somethingSomethingAdder from './maths'
console.log(somethingSomethingAdder(1, 2))
// prints 3
const
You can also name your exports by doing an export const
.
export const
s as you like provided they all have different names.fruits.js
export const banana = "Banana"
import { banana } from './fruits'
export const aNumber = 1
export const myArray = [1,2,3]
export const helloWorld = {hello: "world"}
export const adder = (a, b) => a + b // <--- functions are good :)
export const adder1 = (a, b) => { return a + b }
export 1 //<----ERROR can't export an expression.
myFolder/banana.js
export const banana = "Banana!"
myFolder/fruitBowl.js
import { banana } from './banana'
console.log(banana)
// prints "Banana!"
myFolder/banana.js
export const banana = () => "Banana!"
myFolder/fruitBowl.js
import { banana } from './banana'
console.log(banana())
// prints "Banana!"
myFolder/banana.js
export const banana = () => "Banana!"
export default "Bananananana!"
myFolder/fruitBowl.js
import banananana, { banana } from './banana'
console.log(banananana)
// prints "Bananananana!"
console.log(banana())
// prints "Banana!"
index.js
Import and Exporting has an extra useful trick. If you name a file index.js
you can import it by just mentioning the name of the folder.
banana/index.js
export default "Banana!"
myFile.js
import banana from './banana' // <- just the folder
console.log(banana)
// prints 'Banana!'