자바스크립트/리액트

리액트 코드를 exe 파일로 만들기 (pkg, nexe)

길용쓰 2024. 4. 25. 17:48

목표 -> 리액트로 웹서버를 여는 프로그램을 단독 실행 파일(exe)로 만들기

 

리액트로 코드를 작성하고,

터미널에 npm run build 입력시 

리액트 프로젝트 소스코드가 빌드되어

build 폴더에 index.html과 함께 저장된다.

 

또한 serve -s build로 

빌드된 정적 파일을 로컬 웹 서버로 돌릴 수 있다.

 

-> serve는 npm에 속하는 명령어고 

npm은 node와 같이 설치되기에 결국 node가 필요하다.

node를 깔지 않고 리액트트 프로젝트를 

exe와 같은 단독 실행 파일로 만들려면?

 

 

 

https://velog.io/@khw970421/React-%ED%8C%8C%EC%9D%BC%EB%93%A4%EC%97%90-%EB%8C%80%ED%95%B4%EC%84%9C-index.js-App.js-index.html

 

React 파일들에 대해서 (index.js, App.js ,index.html)

아래내용은 이 분의 블로그에서 참조한 내용이 많다. index.jsApp.jsindex.htmlindex.jssrc 폴더에 포함되어 있다. 메인 프로그램이라고 할 수 있다. 여기에서 HTML 템플릿 및 JavaScript의 컴포넌트를 조합하

velog.io

리액트는 index.js 파일이 소스코드의 시작점처럼 작동하며,

index.js의 내용이 index.html 파일의 <body> <div id='root'> 항목에 들어가 
사용자 화면에 보여지게된다.

 

const express = require('express');
const path = require('path');
const app = express();

// Serve the static files from the React app
const buildPath = path.join(__dirname, 'build');
console.log('Static files directory:', buildPath);
app.use(express.static(buildPath));

// Handles any requests that don't match the ones above
app.get('*', (req, res) => {
    const indexPath = path.join(buildPath, 'index.html');
    console.log('Sending index.html:', indexPath);
    res.sendFile(indexPath);
});

const port = process.env.PORT || 3000;

// Attempt to start the server
try {
    const server = app.listen(port, () => {
        console.log(`App is running on port ${port}`);
    });

    // Keep the server running even if an error occurs
    server.on('error', (err) => {
        console.error('Server error:', err.message);
    });

    // Keep the process running
    process.stdin.resume();
} catch (error) {
    console.error('Server startup error:', error.message);
    // Keep the process running
    process.stdin.resume();
}

index.html을 로컬서버 포트 3000에 띄우는 코드이다.

디버깅 과정중 쓸데없는 사족이 많이 덧붙긴 했는데 쨌든

 

리액트 자체가 index.html에 내용을 담아 웹으로 띄우는 만큼

index.html을 서버로 띄우는 이 코드도 리액트와 동일하게 작동한다.

 

그럼 이를 패키징하여 exe로 만들면?

 

https://www.npmjs.com/package/pkg

 

pkg

Package your Node.js project into an executable. Latest version: 5.8.1, last published: a year ago. Start using pkg in your project by running `npm i pkg`. There are 248 other projects in the npm registry using pkg.

www.npmjs.com

https://blog.outsider.ne.kr/1379

 

pkg로 Node.js 애플리케이션의 하나의 바이너리로 만들기 :: Outsider's Dev Story

[pkg](https://github.com/zeit/pkg)는 [zeit](https://zeit.co/)에서 만든 Node.js 바이너리 컴파일러이다. 보통 Node.js로 애플리케이션을 만들면 실행 머신에 애플리케이션에 맞는 Node.js가 설치되어 있어야...

blog.outsider.ne.kr

 

처음엔 pkg를 썼다.

node20을 지원안하는것같아서 node14로 다운그레이드하니

node.js로만 작동하는 백엔드 서버 파일은 정상적으로 exe 파일로 변환됐다.

 

하지만 위 서버 파일을 pkg 변환해 실행하니

index.html 파일을 도저히 읽을 수 없었고..

(다른 파일을 읽는건 정상적으로 동작했다.)

인터넷에 별에별 글을 다 찾아 시도했지만

결국 실패했다.

 

 

패키징 프로그램으로는 

pkg 말고 nexe란 것도 존재하기에

제작자 github를 뒤져가며 이리저리 굴린 결과

https://github.com/nexe/nexe?tab=readme-ov-file#troubleshooting

 

GitHub - nexe/nexe: 🎉 create a single executable out of your node.js apps

🎉 create a single executable out of your node.js apps - nexe/nexe

github.com

 

 

 

성공했다!