Exports & Imports Modules in React

률루랄라·2020년 1월 24일
0
post-custom-banner

#when export and import modules or components, it was bit confusing with wrapped with brackets while somes are just declared as it is as written in its own script or with other new variable where has been imported.
For example, I saw three cases using React.js such as

import React from 'react
import {Idk} from 'somewhere.js'
import classcomponent from 'Component.js'
So today, I want to get through little deeper with these cases or exporting and importing modules breifly and quickly


default export and named export

person.js

///person.js

const person = {
  name:"Lee"
}

export default person

utility.js

///utility.js

export const clean =()=>{
  //...
}

export const baseData=10;

app.js

///app.js

import person from './person.js'
import prs from './person.js'
//this is default export case

// if a variable(or class) has been declared as default, it could be imported as a variable itself or other variable as want to be used in a script.
import {baseData} from './utility.js'
import {clean} from './ utility.js'
//this is named export case

// it is an example when exporting various variables from a same script.
// in this case, javascript need to be indicated specifically which one or ones will be imported in the script.
// thats why variables are wrapped with brackets

One more Thing with named export


we also can use it like a example below

import { smth } from 'utility.js'
// same as above
import { smth as Smithh } from 'utility.js'
// now js will indicate Smithh as smth from utility.js
import * as bundled from 'utility.js'
// now js will indicate * as bundled from utility.js
// for this case it is useful when whatever variable like to be imported is a object 
// and we would like to approach to values in deep level while variable which assigned as object 
// has a name with long length such as 
// const userDataForInsuranceWithPreminum = {} 
// now we can approach like bundled.key.anotherKey

one more another Thing


This is a kind of method have learned from bootcamp mentor and had been helpful during the project.
This method is simply just creating a new file, named index.js in the same folder with the js file that needed to be exported.

someThing.js

const code =() =>{
  console.log("here is code")
}

export default code

index.js

export { default } from './someThing.js'

and in the script file where to import someThing.js


import code from 'directory until the folder'

in this case, with a huge project which will have trmendous folders and files and makes us to find all the directories in deep depth, I call traffic of Project, we could just wrtie a directory until the folder.

profile
💻 소프트웨어 엔지니어를 꿈꾸는 개발 신생아👶
post-custom-banner

0개의 댓글