Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

React - babel, webpack, react 설치, npm ERR! 본문

React

React - babel, webpack, react 설치, npm ERR!

보람- 2023. 11. 23. 14:11

목차

1. babel 사용법, 환경 설정, 실행

2. babel 변환

3. webpack 속성

4. webpack 설정 & 실행

5. react 실행, 에러


 

 

 

 

 

1. babel 사용법, 환경 설정, 실행

 

- babel은 자바스크립트 코드를 변환해준다.

- commonjs와 ES6문법 전환을 해주어 최신 문법으로 작성하면서 작업을 할수있다는 장점이 있다!

 

 

- npm 설치하기

npm install @babel/core @babel/cli @babel/preset-env

 

 

- .babelrc 파일만들고 환경 구성해주기

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "16",
                    "chrome": "58",
                    "ie": "11"
                }
            }
        ]
    ]
}

- 자바스크립트 기능 또는 구문 변환하는 babel 플러그인

- 프로젝트의 특정 브라우저, node 버전에서도 가능

 

 

 

- app.js파일을 만들고 작성해서 실행해보기 (step01)

npx babel ["변환할 파일 경로"] --out-file ["내보내는 파일명과 경로"]

npx babel app.js --out-file dist/app.js

 

 

 

 

 

 

2. babel 변환

 

① 모듈시스템 변환 (step02)

- 플러그인을 사용해서 commonjs 형식으로 코드를 변환한다!

npm install @babel/core @babel/cli @babel/plugin-transform-modules-commonjs

npx babel server.js --out-file dist/server.js
// .babelrc

{
    "plugins": ["@babel/plugin-transform-modules-commonjs"]
}

 

 

 

② JSX 문법 변환  (step03)

- 리액트 프로젝트에서 기본적인 2가지 속성!

npm install @babel/core @babel/cli @babel/preset-env @babel/preset-react

npx babel app.js --out-file dist/app.js
// .babelrc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

 

 

 

 

 

 

3. webpack 속성

 

- 웹을 구성할때 다양한 파일과 기능을 작성하면 파일들과 기능들을 가지고 웹페이지를 그리는데

- 최소한의 파일만 가지고 컴파일 해준다 → 웹페이지 로딩속도를 개선해서 빨라지는!

 


- 모듈 : 프로그램을 구성하는 요소, 사용하는 데이터와 함수를 하나로 묶은 단위
- 번들러 : 의존성이있는 모듈 코드들을 파일로 만들어주는 도구
   - 컨트롤러가 여러개의 파일들을 하나로 묶어주는 역할
   - 쉽게 node 환경에서 실행되는데 파일을 뽑아주는역할
   - 뽑아주는 파일은 우리가 작성한 코드들을 하나로 뭉쳐주는 역할하는 하는 도구

 

 entry : 설정파일이 필요해, 진입점 지정, 시작점으로 사용할 모듈을 webpack에 알려주는 역할
 output : 내보내는 번들링 방법을 결정, 생성한 번들링 파일위치, 파일의 이름 지정
③ loaders : 번들링 중에 모듈의 소스 코드에 적용되는 js, css, image 경로 파일 처리
④ plugins : 추가로 사용할 플러그인 번들 최적화, html 파일생성, 환경변수env

 

 

 

 

 

4. webpack 설정 & 실행

 

- 설치하기 (step01)

npm install webpack webpack-cli

 

- webpack.config.js 파일 만들고
- node환경에서 실행이되고, 파일을 뽑아주는 내용에서 설정값을 작성한다!!

- 실행하기 

 npx webpack

 

 

 

① entry, output 사용

// node환경에서 실행됨
const path = require("path");

module.exports = {
    // 진입점, 시작점 지정
    entry: "./src/index.js",

    // 번들된 파일을 내보낼 속성 설정
    output: {
        filename: "bundle.js",
        // 생성할 파일의 경로 지정
        path: path.join(__dirname, "dist"),
    },
};

 

 

 

② loader 사용 → style 설정하기 (step02)

- 설치하고 설정하고 실행!

npm install webpack webpack-cli css-loader style-loader
// webpack.config.js

const path = require("path");

module.exports = {
    // 진입점
    entry: "./src/index.js",

    // 모듈 규칙 설정
    module: {
        rules: [
            {
                // 파일 확장자가 일치하는 파일을 찾는 정규식 test
                test: /\.css$/,
                // .css파일을 읽어오고 어떤 오더로 읽을것인지 지정
                // 사용할 로더를 작성
                // style-loader, css-loader : html 문서 header에 style태그를 생성하고 읽고 css코드를 추가해준다
                use: ["style-loader", "css-loader"],
            },
        ],
    },

    // 번들링 된 파일 내보내기 속성
    output: {
        filename: "bundle.js",
        path: path.join(__dirname, "dist"),
    },
};

 

 npx webpack

 

 

 

 

 

③ plugins 사용 (step03)

npm install webpack webpack-cli @babel/core @babel/preset-env @babel/preset-react babel-loader html-webpack-plugin react react-dom
// .babelrc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}
// webpack.config.js

const path = require("path");
const HTMLwebpackPlugin = require("html-webpack-plugin");

module.exports = {
    // 개발 모드 설정
    // 빌드할때 최적화를 할건지 안할건지 ?
    mode: "development",

    // 진입점
    entry: "./src/index.js",

    module: {
        rules: [
            {
                // 읽어올 파일 확장자
                test: /\.(js|jsx)$/,

                // 읽어올 파일중에 제외할 폴더
                exclude: /node_modules/,

                // jsx문법작성하는데 babel-loader 사용
                use: ["babel-loader"],
            },
        ],
    },

    plugins: [
        // HTMLwebpackPlugin 사용해서 index.html 번들링한 폴더에 생성
        new HTMLwebpackPlugin({
            // 변환할 html의 경로
            template: "src/index.html",
            // 번들링되고 파일의 이름
            filename: "index.html",
        }),
    ],

    output: {
        filename: "bundle.js",
        path: path.join(__dirname, "dist"),
    },
};
npx webpack

 

 

 

 

 

 

5. react 실행, 에러

npx create-react-app "설치하는 폴더이름"

npx create-react-app test

- 설치가 된다면 만든 폴더로 이동후 npm start, npm run build하면 브라우저가 실행된다!

 

 

★ ★ ★ ★  react 설치중에 npm ERR!!

→ 해결방법 : 

npm -v, node -v 버전을 확인도 해보고

chatGPT에서 "npm cache clean --force" 알려줘서 입력도 해보고

제어판에 가서 nodejs제거 후 다시 설치하고 결국

mkdir C:\Users\cer-e\AppData\Roaming\npm

npm uninstall -g npm
npm install -g npm

수동으로 폴더를 만들고 npm 삭제 후 다시 받고나서야 npx create-react-app test가 입력되어 다운받아졌다ㅠㅠ

 

 


※ step01,02,03 폴더마다 "dist" 폴더를 만들고 번들링해서 만들어진 js파일을 html src에 넣어 실행시켜서 확인해봤음!!

※ <div id="root"></div> 최초의 한번은 꼭 필요함!!!