21.02.14(+21.02.16)
* react를 create하기 원하는 폴더를 생성한 후 그 폴더에 들어가 아래의 과정 실행
1. package.json 생성
npm init
2. react 생성
npm install react react-dom
또는
yarn add react react-dom
- react : 리액트 라이브러리
- react- dom : 브라우저, dom, webapp 관리
3. babel 생성
npm install --save-dev @babel/core babel-loader @babel/preset-react @babel/preset-env
또는
yarn add --dev @babel/core babel-loader @babel/preset-react @babel/preset-env
- babel : 코드 변환기. 모든 브라우저가 자바스크립트의 최신 문법을 지원하는 게 아니기 때문에 옛날 브라우저에서 최신 문법으로 쓰인 코드가 작동할 수 있도록 문법을 변환시켜주는 코드 변환기가 필요하다. 참고로 리액트는 es6문법을 사용한다.
- babel/core : es6문법을 es5문법으로 변환
- babel/preset-react : jsx를 JavaScript로 변환
- babel/preset-env : 브라우저에 따라 알아서 컴파일. 자세한 것은 여기 참조
- bable-loader : preset/plugin과 webpack을 사용하여 es5로 컴파일해주는 plugin
- --save-dev : 개발환경에서만 사용되는 라이브러리라는 것을 명시
- loaders
- preset : plugins들의 집합. 한 번에 추가하여 plugin들의 개별설정을 피할 수 있음
- plugins : webpack의 핵심기능인 컴파일러. webpack은 기본적으로 source코드를 bundle파일로 변환한다.
플러그인과 로더 모두 최적화를 하지만 플러그인이 더 밀도있는 작업을 수행한다.
4. webpack 설치
npm install --save-dev webpack webpack-dev-server webpack-cli html-webpack-plugin
- webpack : 모듈 번들러
- webpack-dev-server : live서버 reload
- webpack-cli : build 스크립트를 통해 웹팩 커맨드를 사용하기 위한 것
- html-webpack-plugin : webpack.config.js에서 사용할 플러그인
4-1. webpack.config.js 생성
package.json파일이 있는 위치에 webpack.config.js 파일을 생성한다
밑의 코드에서 주석을 빼야함.
webpack.config.js
const path = require('path') // core nodejs 모듈 중 하나, 파일 경로 설정할 때 사용
const HtmlWebpackPlugin = require('html-webpack-plugin') // index.html 파일을 dist 폴더에 index_bundle.js 파일과 함께 자동으로 생성, 우리는 그냥 시작만 하고싶지 귀찮게 index.html 파일까지 만들고 싶지 않다.!!
module.exports = { // moduel export (옛날 방식..)
entry: './src/index.js', // 리액트 파일이 시작하는 곳
output: { // bundled compiled 파일
path: path.join(__dirname, '/dist'), //__dirname : 현재 디렉토리, dist 폴더에 모든 컴파일된 하나의 번들파일을 넣을 예정
filename: 'index_bundle.js'
},
module: { // javascript 모듈을 생성할 규칙을 지정 (node_module을 제외한.js 파일을 babel-loader로 불러와 모듈을 생성
rules: [
{
test: /\.js$/, // .js, .jsx로 끝나는 babel이 컴파일하게 할 모든 파일
exclude: /node_module/, // node module 폴더는 babel 컴파일에서 제외
use:{
loader: 'babel-loader' // babel loader가 파이프를 통해 js 코드를 불러옴
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html' // 생성한 템플릿 파일
})
]
}
- 1행 : 패스(파일 경로) 설정시 사용. core node.js 모듈 중 하나이다.
- 2행 : index.html 파일을 dist 폴더에 index_bundle.js 파일과 함께 자동으로 생성
- 5행 : 리액트 파일이 시작하는 곳
5. index.html 생성
index.html 파일을 src/index.html 경로로 생성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>React App</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
6. babelrc
루트 디렉토리에 .babelrc 파일 생성
babel.config.js
module.exports = {
presets: ["@babel/env", "@babel/react"],
};
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './component/App';
ReactDOM.render(<App/>, document.getElementById('app'));
* 5행 : dom에 render할 메인 app component 또는 rendering할 곳.
App.js
import React from 'react';
class App extends React.Component {
render(){
return(
<div>
<h1>React App</h1>
</div>
);
}
}
export default App;
package.json에 scripts를 다음으로 변경
"scripts": {
"start":"webpack-dev-server --mode development --open --hot",
"build":"webpack --mode production"
},
- --open : 자동으로 브라우저 열어줌
- --hot : hot reload. 저장했을 때 자종적으로 reload해줌.
- 3행 : dist 폴더에 컴파일된 파일 다 넣어줌
7. 프로젝트 실행 및 빌드
7-1. 프로젝트 실행
npm start
React App이라고 써져있는 화면이 출력된다.
7-2. 프로젝트 빌드
npm run build
프로젝트 폴더에 /dist 폴더가 생기게 된다.
8. /dist 폴더
dist폴더 안에는 index_bundel.js 와 index.html이 생긴다.
---------------------문제점과 해결-----------------------
1. Cannot find module 'webpack-cli/bin/config-yargs' 오류가 난다.
원인 : webpack과 webapck-dev-server간의 버전이 맞지 않아서
해결 : npm uninstall -D webpack webpack-cli
npm install -D webpack webpack-cli
2. module에 빨간줄
해결 : .eslintrc.json안에 rule에 "@typescript-eslint/no-var-requires": 0 추가
3. require과 __dirname 등에 빨간줄
해결 : .eslintrc.json안에 rule에 "@typescript-eslint/explicit-function-return-type": 'off' 추가
4. render()에 노란줄
원인 : 이것도 eslint문제인거같긴한데 마땅한 방법이 안나온다. explicit-module-boundary 오류.
해결 : 전구 눌러서 해결
'FE > react' 카테고리의 다른 글
| React와 TypeScript 초기세팅 (0) | 2023.07.19 |
|---|---|
| React 이미지 경로 img src에 추가 (0) | 2021.03.05 |
| React 배열 렌더링, useRef 로 컴포넌트 안의 변수 만들기 (0) | 2021.02.10 |
| React useRef (0) | 2021.02.10 |
| React useState를 이용한 Counter만들기 (0) | 2021.02.05 |