0215 [REACT] import와 export
var1.js
let name = '가길동'
var2.js
let name = '나길동'
순서에 따라 다르다!!!!
test.html
<script src="var2.js" ></script>
<script src="var1.js"></script>
<script>
console.log(name) // 이러면 나길동 출력
</script>
<h1>클래스연습</h1>
<script src="var1.js"></script>
<script src="var2.js" ></script>
<script>
console.log(name) // 이러면 가길동 출력
</script>
<h1>클래스연습</h1>
-CommonJS스펙에서는 모듈을 가져올때 require()함수, 모듈를 내보낼때는
module.exports나 exports.함수명 형태로 사용한다.그러나
ES6에는 외부 모듈의 함수나 객체를 가져올때는 import 내보낼때는 export를 사용한다.
-모듈이 동일한 폴더에 있더라도 "모듈명.js"는 에러발생
즉 "./ 모듈명.js", "../모듈명.js" "/모듈명.js" 으로 사용해야 한다! 생략하면 안된다고 !!
default import방식이 named import방식보다 앞에 와야한다 즉 별칭1,별칭2,..,{}형태여야한다
가.named import방식
-import {name} from "모듈파일"; 형식으로 불러온다
-name은 모듈에 있는 함수나 객체등이다 그래서 이름을 임의로 할 수 없다
나.default import방식
-name은 임의로 바꿀수 있고 { }가 없다
-내보는 모듈 파일안에서 export default는 한 번만 사용가능하다.
다.모듈을 불러올때 named import와 default import방식을 혼합 할 수 있다
-import name,{name1},{name2} from "모듈파일"
다른 모듈에서 함수나 객체등을 내보낼때는 export 와 export default 를 함께 사용하면 된다
단, default export 된 객체를 가져오는 부분이 먼저 선언되야 한다.
파일, 폴더는 요렇게 구성
circle.js
/*
const circle = function(r){
return Math.PI*r*r;
}*/
export const circle = r => Math.PI*r*r;
rectangle.js
export const widthHeight={width:100, height:100}
export const rect =() => console.log('사각형입니다.')
export default function ares(width,height){
return width*height;
}
triangle.js
export let width=100
export let height=100
export const 면적 = (width,height)=> width*height*0.5;
console.log('삼각형 가로폭:',width)
console.log('삼각형 세로폭:',height)
console.log('삼각형 면적:',면적(100,100))
index.js
import {circle} from "./js/circle.js";
import ares,{widthHeight as 폭, rect} from './js/rectangle.js';
//import * as tri from './js/triangle.js';
import "./js/triangle.js" //바로 실행할 목적이라면 요렇게 쓰고
//import {width,hight,면적} from './js/triangle.js';
const index = function(){
console.log(circle(100));
console.log('가로폭:%s,세로폭:%s',폭.width,폭.height);
rect()
console.log(ares(100,100));
//import * as tri from './js/triangle.js'; 일 때
/* console.log('삼각형 가로폭:',tri.width)
console.log('삼각형 세로폭:',tri.height)
console.log('삼각형 면적:',tri.면적(100,100)) */
//import {width,hight,면적} from './js/triangle.js'; 일 때
/* console.log('triangle 가로폭:',width)
console.log('triangle 세로폭:',height)
console.log('triangle 면적:',면적(100,100)) */
}
export default index
/*
요렇게 해도 가능
export function index(){
console.log(circle(100));
}
혹은 요거도 가능
const index = function(){
console.log(circle(100));
}
*/
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!--
<script src="index.js">
// 요건 페이지 방식으로 저 페이지에 있는걸 고대로 가져오는 것
</script>
-->
<script type="module">
// 요건 모듈방식임 !
import module from './index.js'
console.log(module())
</script>
</head>
<body>
<h2>모듈방식 연습</h2>
</body>
</html>