Vite 설정은 npm, yarn, pnpm으로도 가능하다.
CRA앱과 다른 점은 npm install을 해주지 않고 직접 해줘야 한다.
npm create vite@latest
or
yarn create vite
or
pnpm create vite
위와 같이 입력한 후 UI Framework나 사용언어를 고를 수 있고 아래와 같이 바로 실행할 수 있는 명령어도 있다.
# npm 6.x
npm create vite@latest my-vue-app --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue
# yarn
yarn create vite my-vue-app --template vue
# pnpm
pnpm create vite my-vue-app --template vue
template은 아래와 같이 지정한다.
vanilla, vanilla-ts,
vue, vue-ts,
react, react-ts,
preact, preact-ts,
lit, lit-ts,
svelte, svelte-ts
이제 만들었던 폴더로 들어가서 npm install을 실행하여 Node 모듈을 설치하면 서버를 실행시킬 수 있다.
cd vite-project
npm install
npm run dev
CRA는 webpack으로 번들링하기 때문에 코드가 변경되면 모든 js코드를 새로 번들링한다. 따라서 앱이 커질수록 HMR(Hot Module Reloading)이 느려진다.
Vite는 esbuild를 이용해서 변경된 부분만 새로 번들링하기 때문에 CRA에 비해 속도가 빠르다.
my-app/
|- node_modules/
|- public/
| |- index.html
|- src/
| |- main.js
|- package.json
|- vite.config.js
my-app/
|- node_modules/
|- public/
| |- index.html
| |- ...
|- src/
| |- App.js
| |- index.js
| |- ...
|- package.json
|- ...
CRA앱에서 아래와 같이 import 했다면
import Cards from "components/cards";
Vite에서는 절대경로로 import 해야한다.
import Cards from “/src/components/cards.jsx”
3.React의 환경변수
//예전 방식
REACT_APP_ API_KEY = 1234567890..
// Vite에서 쓰는 방식
VITE_API_KEY = 1234567890..
이것은 vite 플러그인 중에서 vite-plugin-env-complate 패키지를 쓰면 해결할 수 있다.
npm install vite-plugin-env-compatible
vite.config.js 파일을 아래와 같이 수정하면 된다.
import envCompatible from 'vite-plugin-env-compatible';
export default defineConfig({
...
envPrefix: 'REACT_APP_',
plugins: [
react(),
envCompatible
],
});
위와 같이 하면 REACTAPP 으로 시작하는 환경변수도 Vite에서 인식할 수 있습니다.
그리고 중요한 게 바로 process.env 방식이 아니라 import.meta.env를 이용해서 환경변수에 접근해야 한다.
// 예전 CRA 방식
process.env.REACT_APP_API_KEY
// Vite 방식
import.meta.env.VITE_API_KEY
실제 프로젝트 초기세팅 시
.eslintrc.cjs 파일에서 에러 발생
.eslintrc.cjs 파일에서 "module is not defined" 오류가 발생하는 이유는 해당 파일에서 ES 모듈 시스템을 사용할 수 없기 때문입니다.
.eslintrc.cjs 파일은 CommonJS 모듈 시스템을 사용하여 구성 파일을 로드하는 데 사용됩니다. 그러나 Vite 프로젝트에서는 기본적으로 ES 모듈 시스템을 사용하므로 .eslintrc.cjs 파일을 사용하는 것은 적절하지 않습니다.
Vite와 TypeScript를 사용하여 React 프로젝트를 설정할 때, ESLint 설정 파일을 .eslintrc.cjs 대신 .eslintrc.json 또는 .eslintrc.js로 사용하는 것이 일반적입니다. 이러한 파일 형식은 ES 모듈 시스템을 지원하고, TypeScript와 함께 사용할 수 있는 모듈 선언을 할 수 있습니다.
=>해결 방법
{
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"plugins": ["react", "@typescript-eslint"],
"rules": {
// 여기에 추가적인 규칙을 설정할 수 있습니다.
}
}