반응형

이 포스트의 동영상 강의

https://youtu.be/7hzH4B6xLIE

 

Electron

이번 글은 일렉트론 공식 홈페이지에 있는 퀵스타트를 요약한 것입니다.

https://www.electronjs.org/docs/latest/tutorial/quick-start

 

Quick Start | Electron

This guide will step you through the process of creating a barebones Hello World app in Electron, similar to electron/electron-quick-start.

www.electronjs.org

nodejs

Nodejs 설치 및 업데이트

  • Electron을 개발하기 위해서는 우선 nodejs가 설치 되어 있어야 합니다.
  • nodejs 홈페이지에서 nodejs를 설치합니다.
  • https://nodejs.org/ko/
  • 설치 후 다음 명령을 사용하여 설치 버전을 확인합니다.

 

node -v
npm -v​

 프로젝트 폴더 생성

  • mkdir my-electron-app 
  • cd my-electron-app

프로젝트 생성

  • npm init

Package.json 파일 확인

{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": “First electron app",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
  • "main": "index.js" : entry point로 프로그램의 시작점입니다.
  • 파일명은 index.js 또는 main.js를 일반적으로 사용합니다.

Electron Package 추가

  • 프로젝트에서 electron을 사용하기 위해서는 "electron" 패키지를 반드시 추가해야 합니다.
npm install --save-dev electron

Package.json에 script 추가

  • 실행 스크립트를 다음과 같이 추가합니다.
  • npm start로 스크립트를 실행할 수 있습니다.
    "scripts": { 
        "start": "electron ." 
    }

index.html 생성

  • root 폴더에 index.html을 만들고 다음과 같이 작성합니다.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.
  </body>
</html>

index.js 생성

  • root 폴더에 index.js를 만들고 다음과 같이 작성합니다.
const { app, BrowserWindow } = require('electron')
// include the Node.js 'path' module at the top of your file
const path = require('path')


// modify your existing createWindow() function
function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })
  win.loadFile('index.html')
}
app.whenReady().then(() => {
  createWindow()
})
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

preload.js 생성

  • root 폴더에 preload.js를 생성 합니다.
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency])
  }
})

프로젝트 실행

npm start

실행 화면

Electron 실행

패키징과 배포

  • 패키징과 배포를 위한 가장 빠른 방법은 Electron Forge를 사용하는 것입니다.
  • Electron Forge 패키지를 추가합니다.
npm install --save-dev @electron-forge/cli
npx electron-forge import
  • Forge의 "make"를 이용하여 빌드합니다.
npm run make
  • 실행 파일의 위치는 다음과 같습니다.
\out\my-electron-app-win32-x64\my-electron-app.exe

이상으로 Electron Quick Start를 마칩니다.

반응형
반응형

이 포스트의 동영상 강의

https://youtu.be/Krc4mHkGLqM

 

 

 

일렉트론

일렉트론은 Javascript, HTML, CSS를 이용하여 Desktop Application을 만드는 프레임워크입니다.

따라서 자바스크립트와 웹개발 지식을 가지고 있다면 쉽게 데스크톱 애플리케이션을 만들 수 있습니다.

그리고, 일렉트론은 1개의 코드만으로 Cross-Platform에서 작동하는 애플리케이션을 빌드할 수 있습니다.

 

일렉트론은 

  • 2013.4 Atom Editor를 만들기 위해 시작한 Atom Shell에서 시작
  • 2014.5 MIT라이선스 오픈소스로 전환
  • 2015.4 Atom Shell에서 Electron으로 명칭 변경
  • 2016.5 Electron V1.0 출시

일렉트론 아키텍처

  • Backend - Nodejs 런타임
  • Frontend -Chromium(크로미엄, 오픈소스 웹브라우저 프로젝트이며 구글 크롬이 이것을 사용함)

Electron Architecture

일렉트론을 사용하여 만들어진 Application

  • 일렉트론을 이용해 개발된 앱은 https://www.electronjs.org/apps 에서 확인할 수 있습니다.
  • 굉장히 많은 앱 리스트가 있고, 그 중 우리가 잘 아는 앱들은 다음과 같은 것들이 있습니다.

Electron으로 개발된 Application

일렉트론 Application의 File 구조

Electron Application Files

일렉트론의 장점

  • 웹기술을 이용해 Desktop Application 개발이 가능.
  • 한개의 코드로 Cross platform에서 작동하는 애플리케이션을 만들 수 있음.
  • NPM을 이용해 node package들을 사용할 수 있음.
반응형
반응형

React 소스 분석을 위해 에디터는 VSCode(Visual Studio Code)를 사용합니다.

  • 우선 VSCode를 실행합니다.
  • 메뉴-파일-폴더열기를 선택하고 생성한 프로젝트 폴더를 선택합니다.
    예) C:\workspace\my-first-react-app

폴더 열기

  • 폴더 구조

  • index 페이지 호출 구조

index 페이지 호출 구조

  • App.js 분석

App.js 분석

반응형
반응형

 

이 포스트의 동영상 강의 URL

https://youtu.be/BRDw_rJ74vY

 

 

리액트 프로젝트를 만들기

  • npx create-react-app s3-react-file-upload

패키지 추가

  • npm i aws-sdk
  • npm i reactstrap

컴포넌트 생성

  • S3Upload.js

코드 작성

  • import
import './App.css';
import {useState} from "react";
import AWS from 'aws-sdk';
import { Row, Col, Button, Input, Alert } from 'reactstrap';
  • 변수 선언
const [progress , setProgress] = useState(0);
const [selectedFile, setSelectedFile] = useState(null);
const [showAlert, setShowAlert] = useState(false);
  • s3 정보를 설정합니다.
const ACCESS_KEY = 'IAM의 ACCESS KEY';
const SECRET_ACCESS_KEY = 'IAM의 SECRET ACCESS KEY';
const REGION = "ap-northeast-2";
const S3_BUCKET = 'codegear-react-file-upload-test-bucket';

AWS.config.update({
  accessKeyId: ACCESS_KEY,
  secretAccessKey: SECRET_ACCESS_KEY
});

const myBucket = new AWS.S3({
  params: { Bucket: S3_BUCKET},
  region: REGION,
});
  • 파일 선택시 function
const handleFileInput = (e) => {
  const file = e.target.files[0];
  const fileExt = file.name.split('.').pop();
  if(file.type !== 'image/jpeg' || fileExt !=='jpg'){
    alert('jpg 파일만 Upload 가능합니다.');
    return;
  }
  setProgress(0);
  setSelectedFile(e.target.files[0]);
}
  • upload 버튼 click시 function
const uploadFile = (file) => {
  const params = {
    ACL: 'public-read',
    Body: file,
    Bucket: S3_BUCKET,
    Key: "upload/" + file.name
  };
  
  myBucket.putObject(params)
    .on('httpUploadProgress', (evt) => {
      setProgress(Math.round((evt.loaded / evt.total) * 100))
      setShowAlert(true);
      setTimeout(() => {
        setShowAlert(false);
        setSelectedFile(null);
      }, 3000)
    })
    .send((err) => {
      if (err) console.log(err)
    })
}

html

 return (
    <div className="App">
      <div className="App-header">
        <Row>
          <Col><h1>File Upload</h1></Col>
        </Row>
      </div>
      <div className="App-body">
        <Row>
          <Col>
            { showAlert?
              <Alert color="primary">업로드 진행률 : {progress}%</Alert>
              : 
              <Alert color="primary">파일을 선택해 주세요.</Alert> 
            }
          </Col>
        </Row>
        <Row>
          <Col>
            <Input color="primary" type="file" onChange={handleFileInput}/>
            {selectedFile?(
              <Button color="primary" onClick={() => uploadFile(selectedFile)}> Upload to S3</Button>
            ) : null }
          </Col>
        </Row>
      </div>
    </div>
  );

App.css

.App-body {
  background-color: #6d7b97;
  min-height: 50vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-body .alert-message {
  height: 50px;
  background-color: #61dafb;
}

App.js에 S3Upload 컴포넌트 추가

App.js에 S3Upload 컴포넌트를 추가합니다.

  return (
    <S3Upload/>
  );

빌드

터미널에서 다음 스크립트를 실행합니다.

npm run build
빌드 후 프로젝트폴더/build에 생성 된 파일들

build 파일들

 

s3에 애플리케이션 업로드

build 폴더 아래에 있는 모든 파일을 s3에 업로드합니다.

S3에 빌드 파일 업로드

index.html URL 확인

index.html을 클릭해서 속성의 url을 확인한 후 브라우저에서 실행합니다.

index.html url 확인

권한 설정 변경

아래와 같이 접근오류가 발생할 경우

접근 오류

s3에 업로드한 모든 파일을 선택후 -> 퍼블릭으로 설정해줍니다.

퍼블릭 설정

최종화면

다시 index.html에 접속해보시면 다음과 같이 화면이 나옵니다.

최종화면

반응형
반응형

 

이 포스트의 동영상 강의 URL

https://youtu.be/-BmF30R_erk

 

AWS의 S3는 단순 Storage 제공 서비스입니다.

EC2와 같이 프로그램을 실행시킬 수는 없고, 파일을 업로드하거나 html과 같은 정적 페이지는 서비스 할 수 있습니다.

React로 file upload 기능을 하는 애플리케이션을 S3에서 서비스 하는 기능을 만들어보겠습니다.

 

S3 버킷 만들기

  • aws에 로그인 한 후 검색창에 s3를 입력합니다.
    S3를 선택합니다
    aws s3
  • 버킷 만들기를 클릭합니다.
    버킷만들기
  • 버킷 이름을 입력합니다. (버킷 이름은 리전을 통틀어 유일한 이름만 사용 가능합니다)
    버킷 이름 : codegear-react-file-upload-test-bucket
    버킷 이름 입력
  • 테스트용도이므로 퍼블릭 액세스 차단 설정을 해제합니다.
    퍼블릭 액세스 차단 비활성화(테스트용도)
  • 버킷 만들기를 클릭합니다.
    아래와 같이 버킷이 만들어 집니다.
    버킷 생성
  • 버킷 이름을 클릭하면 파일 업로드를 할 수 있는 화면이 나옵니다.
  • 권한-CORS에 다음을 입력합니다.
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT",
            "POST",
            "HEAD"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "x-amz-server-side-encryption",
            "x-amz-request-id",
            "x-amz-id-2"
        ],
        "MaxAgeSeconds": 3000
    }
]
  • 이제 S3의 사용 준비가 완료되었습니다.
반응형

+ Recent posts