✨리액트 프로젝트 생성하는 3가지 방법과 왜 Vite를 사용하는지 알아보기
한 줄의 명령어 입력으로 React 프로젝트 개발에 필수요소를 자동으로 구성하는 방법입니다!
CRA로 리액트 프로젝트를 셋업하는 법은
윈도우는 git bash 또는 power shell 에서
mac os는 터미널(zsh)에서 아래 코드를 입력하시면 됩니다.
yarn create react-app [원하는 프로젝트 이름]
그러고 Success! 라는 성공 메세지를 확인하고
cd react-cra-app
yarn start
이렇게 CRA를 활용해 바로 프로젝트를 생성할 수 있습니다.
vite란?
✨ Vite 역시, CRA와 같이 리액트 프로젝트를 풀 세팅해주는 빌드 도구이다.
✨ WebPack을 사용하는 CRA 대신 Esbuild를 사용한다.
Vite는 프론트엔드 개발을 위해 새로운 빌드 도구로써
Vite는 원래 Vue.js 애플리케이션을 위해 만들어졌지만,
현재는 React, Svelte, Vanilla JS 등 다양한 프레임워크와 라이브러리를 지원합니다.
빠른 콜드 스타트와 HMR (Hot Module Replacement)
속도 측면에서 기존 CRA와는 비교가 되지 않을 정도로 빠릅니다.
CRA는 기본적으로 설정을 숨기지만, Vite는 사용자가 필요에 따라 설정을
더 쉽게 조정할 수 있습니다.
다음은
Esbuild를 사용하는데 Go 언어 베이스의 자바스크립트 빌드 툴입니다.
CRA가 채택하는 웹팩과 비교할 때, 말이 안되는 수준의 속도를 보여줍니다.
Vite로 리액트 프로젝트 셋업하는 법은
yarn create vite my-react-app --template react
Done. 이라는 글씨가 확인되면
cd my-react-app
yarn
yarn dev
를 통해 Vite로 프로젝트를 생성합니다.
mkdir my-react-app
cd my-react-app
npm init -y
yarn add react react-dom
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
{
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000
}
};
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
import React from 'react';
function App() {
return <h1>Hello, React!</h1>;
}
export default App;
"scripts": {
"start": "webpack serve --open",
"build": "webpack --mode production"
}
✨Vite로 만들어진 React 프로젝트의 구조와 주요 코드를 살펴봅시다.
index.html 의 경우 SPA 에는 html 파일이 한 개만 존재한다.
React 프로젝트에는 index.html 파일 한 개만 존재하고,
<script type="module" src="/src/main.jsx"></script>
위의 코드를 통해 main.jsx 파일로부터 CSR 방식으로 UI를 구성/변경합니다.
main.jsx의 경우
index.html 파일에서 main.jsx 파일을 사용하고, main.jsx파일은 App.jsx 파일을
불러와서 사용하고 있습니다.
App.jsx의 경우
처음 Vite나 React 프로젝트 설정하면 보는 화면의 코드가 적혀있는 곳이다.
✨파일을 생성하다보면, 상대경로 때문에 힘든 상황이 생기는걸 방지하기 위해 경로별칭 옵션을 설정한다.
// vite.config.js파일 수정
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: [
{
find: "@",
replacement: "/src",
},
],
},
});
// jsconfig.json 파일 생성 후 작성
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}