electron 시작해보기
				Programing 미분류  : 
				2020. 12. 14. 23:24
			
		반응형
    
    
    
  기본적으로 공식 싸이트에서 하라는 대로 먼저 해본다.
https://www.electronjs.org/docs/tutorial/quick-start
여기 가서 순서대로 해본다.
 lionel.j  ~
     nvm list
->     v14.15.1
default -> lts/* (-> v14.15.1)
iojs -> N/A (default)
unstable -> N/A (default)
node -> stable (-> v14.15.1) (default)
stable -> 14.15 (-> v14.15.1) (default)
lts/* -> lts/fermium (-> v14.15.1)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.17.1 (-> N/A)
lts/carbon -> v8.17.0 (-> N/A)
lts/dubnium -> v10.23.0 (-> N/A)
lts/erbium -> v12.20.0 (-> N/A)
lts/fermium -> v14.15.1
 lionel.j  ~
     node -v
v14.15.1
 lionel.j  ~
     npm -v
6.14.8
 lionel.j  ~
     nvm current
v14.15.1
기본 electron app 의 구조는
my-electron-app/
├── package.json
├── main.js
└── index.html
이렇다.
작업 디렉토리를 만든다.
 lionel.j  ~/Dev/node
     mkdir my-electron-app && cd my-electron-app
npm init을 해주면 기본 packge.json 파일이 구성 된다.
 lionel.j  ~/Dev/node/my-electron-app
     npm init -y
Wrote to /Users/lionel.j/Dev/node/my-electron-app/package.json:
{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
일렉트론 개발 구성을 한다.
node_modules폴더가 생성되고 그 안에는 electron모듈 설치된 것을 확인할 수 있다. 그리고 다시 package.json을 열어보면 devDependencies에 electron가 추가된 것을 볼 수 있다. 이는 electron를 설치할 때 --save-dev옵션을 추었기에 추가가 된 것이다.
 lionel.j  ~/Dev/node/my-electron-app
     npm i --save-dev electron
> core-js@3.8.1 postinstall /Users/lionel.j/Dev/node/my-electron-app/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"
> electron@11.1.0 postinstall /Users/lionel.j/Dev/node/my-electron-app/node_modules/electron
> node install.js
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN my-electron-app@1.0.0 No description
npm WARN my-electron-app@1.0.0 No repository field.
+ electron@11.1.0
added 89 packages from 99 contributors and audited 89 packages in 5.026s
6 packages are looking for funding
  run `npm fund` for details
found 0 vulnerabilities
그러면 이렇게 만들어 진다.
 lionel.j  ~/Dev/node/my-electron-app
     ls -al
total 64
drwxr-xr-x   5 lionel.j  staff    160 12 15 10:19 .
drwxr-xr-x   7 lionel.j  staff    224 12 15 10:19 ..
drwxr-xr-x  88 lionel.j  staff   2816 12 15 10:19 node_modules
-rw-r--r--   1 lionel.j  staff  27969 12 15 10:19 package-lock.json
-rw-r--r--   1 lionel.j  staff    283 12 15 10:19 package.json
파일 두개를 만든다.
index.js 파일
내용은 이렇게.
----------------------------------------------------
const { app, BrowserWindow } = require('electron')
function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
  win.loadFile('index.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
----------------------------------------------------
다음 하나는 index.html
----------------------------------------------------
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body style="background: white;">
    <h1>Hello World!</h1>
    <p>
        We are using node <script>document.write(process.versions.node)</script>,
        Chrome <script>document.write(process.versions.chrome)</script>,
        and Electron <script>document.write(process.versions.electron)</script>.
    </p>
</body>
</html>
----------------------------------------------------
그리고나서 package.json 을 다음과 같이 고친다.
 lionel.j  ~/Dev/node/my-electron-app
     cat package.json
----------------------------------------------------
{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
     "start": "electron ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron": "^11.1.0"
  }
}
----------------------------------------------------
그리고 나서 npm start 하면 앱이 실행 됨
 lionel.j  ~/Dev/node/my-electron-app
     npm start
> my-electron-app@1.0.0 start /Users/lionel.j/Dev/node/my-electron-app
> electron .
앱을 배포하고 싶을때는
$ npx @electron-forge/cli import
$ npm run make
이렇게 하면
// Example for MacOS
out/
├── out/make/zip/darwin/x64/my-electron-app-darwin-x64-1.0.0.zip
├── ...
└── out/my-electron-app-darwin-x64/my-electron-app.app/Contents/MacOS/my-electron-app
이렇게 생긴다.
그런데 그냥 이렇게 만들면 썡으로 다 해야되서 vue 나 react 같은거를 붙인 boilerplate 를 쓰는것 같다.
인터넷을 찾아보니 vue 를 많이 써서 이걸로 해보려고 한다.
https://github.com/SimulatedGREG/electron-vue
문서는 여기서 참고한다.
https://simulatedgreg.gitbooks.io/electron-vue/content/ko/
# Install vue-cli and scaffold boilerplate  우선 vue-cli를 global 로 설치한다.
npm install -g vue-cli
# 그 다음으로 vue init simulatedgreg/electron-vue my-project 명령을 실행한다.
# 그러면 프로젝트 세팅사항에 대해 물어보는데 적당히 골라서 써준다.
 lionel.j  ~/Dev/node/vue-app-1
     vue init simulatedgreg/electron-vue my-project
? Application Name my-prj1
? Application Id net.hybridego.test1
? Application Version 0.0.1
? Project description An electron-vue project
? Use Sass / Scss? Yes
? Select which Vue plugins to install axios, vue-electron, vue-router, vuex, vuex-electron
? Use linting with ESLint? Yes
? Which ESLint config would you like to use? Standard
? Set up unit testing with Karma + Mocha? Yes
? Set up end-to-end testing with Spectron + Mocha? Yes
? What build tool would you like to use? builder
? author lionel.j <l.j@kakaoenterprise.com>
   vue-cli · Generated "my-project".
---
All set. Welcome to your new electron-vue project!
Make sure to check out the documentation for this boilerplate at
https://simulatedgreg.gitbooks.io/electron-vue/content/.
Next Steps:
  $ cd my-project
  $ yarn (or `npm install`)
  $ yarn run dev (or `npm run dev`)
이렇게 나오면 하라는대로 한다.
# Install dependencies and run your app
cd my-project
yarn # or npm install
yarn run dev # or npm run dev
yarn 이 없으면 npm으로 하던지 아니면 yarn 을 설치한다.
$ brew install yarn
리눅스에서는 cmdtest 를 깔으라고 하는데 그렇게 하면 안되고
$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - 
$ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
$ sudo apt update && sudo apt install yarn 
이렇게 하던가 아니면 npm으로 설치 한다.
$ sudo npm install -g yarn
설치가 다 되었으면 계속한다.    
원래는 
yarn run dev
를 하면 앱이 딱 떠야 하는데 무슨 에러가 난다.
  ERROR in Template execution failed: ReferenceError: process is not defined
  ERROR in   ReferenceError: process is not defined
    - index.ejs:11 eval
      [.]/[html-webpack-plugin]/lib/loader.js!./src/index.ejs:11:2
    - index.ejs:16 module.exports
      [.]/[html-webpack-plugin]/lib/loader.js!./src/index.ejs:16:3
    - index.js:284
      [my-project]/[html-webpack-plugin]/index.js:284:18
    - runMicrotasks
    - task_queues.js:93 processTicksAndRejections
      internal/process/task_queues.js:93:5
여기 나온대로 수정을 해보자.
 https://github.com/SimulatedGREG/electron-vue/issues/871
이 파일 하나를 고치면 된다.
.electron-vue/webpack.renderer.config.js
이걸 열고 HtmlWebpackPlugin 로 검색하면
이런 부분이 나오는데 
  plugins: [
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({filename: 'styles.css'}),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(__dirname, '../src/index.ejs'),
      <<=== 요기다가 추가
      minify: {
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true
      },
      nodeModules: process.env.NODE_ENV !== 'production'
        ? path.resolve(__dirname, '../node_modules')
        : false
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  ],
  이렇게 바꿉니다.
      new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(__dirname, '../src/index.ejs'),
      -----여기부터
      templateParameters(compilation, assets, options){
        return {
          compilation: compilation,
          webpack: compilation.getStats().toJson(),
          webpackConfig: compilation.options,
          htmlWebpackPlugin: {
            files: assets,
            options: options
          },
          process,
        };
      },
      -----여기까지 추가
      minify: {
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true
      },
그리고 다시 실행하면 된다.
$ yarn run dev
실행 파일로 만들려면
$ yarn run build 하면 된다.
아니면 electron-builder 같은걸 써도 된다.
electron-builder로 빌드하기 (https://www.electron.build/)
다음 명령어로 설치한다.
yarn add electron-builder --dev
package.json 에다가 build 옵션을 설정한다.
대략 
"build": {
    "asar": false,
    "appId": "com.project",
    "productName": "Project",
    "win": {
      "target": [
        {
          "target": "nsis",
          "arch": [
            "x64",
            "ia32"
          ]
        }
      ],
      "icon": "./resources/installer/Icon.ico"
    },
    "nsis": {
      "oneClick": true,
      "perMachine": false,
      "installerIcon": "resources/installer/Icon.ico",
      "createDesktopShortcut": true
    }
  }
  다른 옵션들도 있으니 찾아서 설정해본다.
  기본으로 electron-vue boilerplate 에서 build 옵션들이 설정되어 있다. 
  빌드 하려면 다음의 명령을 실행하면 된다.
  ./node_modules/.bin/electron-builder build
 ✘ lionel.j  ~/Dev/node/vue-app-1/my-project
     ./node_modules/.bin/electron-builder build
  • electron-builder  version=22.9.1 os=19.6.0
  • loaded configuration  file=package.json ("build" field)
  • writing effective config  file=build/builder-effective-config.yaml
  • packaging       platform=darwin arch=x64 electron=2.0.18 appOutDir=build/mac
  • skipped macOS application code signing  reason=cannot find valid "Developer ID Application" identity or custom non-Apple code signing certificate, see https://electron.buidmg 파일과 zip 파일까지 다 만들어준다.ld/code-signing allIdentities=
                                                   0 identities found
                                                Valid identities only
                                                   0 valid identities found
  • building        target=macOS zip arch=x64 file=build/my-prj1-0.0.1-mac.zip
  • building        target=DMG arch=x64 file=build/my-prj1-0.0.1.dmg
  • building block map  blockMapFile=build/my-prj1-0.0.1.dmg.blockmap
  • building embedded block map  file=build/my-prj1-0.0.1-mac.zip
결과물은 my-project/build/mac/my-prj1.app 에 생기고
dmg 파일과 zip 파일까지 다 만들어준다.
yarn add serialport
하면 package.json 에 
  "dependencies": {
    "axios": "^0.18.0",
    "serialport": "^9.0.3",
    "vue": "^2.5.16",
    "vue-electron": "^1.0.6",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1",
    "vuex-electron": "^1.0.0"
  },
이렇게 추가 된다.
bootstrap 추가한다. 이 세개는 무슨 차이일까?
yarn add bootstrap
yarn add bootstrap --dev
yarn add bootstrap --save-dev
하다보니 renderer 쪽에서는 console.log 가 출력이 안된다. 찾아보니 이런걸 써야 나온다고 한다.
yarn add electron-log
쓸때는 
const log = require('electron-log')
log.info('this is info')
log.warn('this is warn')
log.error('this is error')
log.verbose('this is verbose')
log.debug('this is debug')
log.silly('this is silly')
이렇게 하면 된다.
반응형
    
    
    
  'Programing 미분류' 카테고리의 다른 글
| Mac 에서 node 완전히 삭제하기 - nvm으로 재설치 (0) | 2020.12.15 | 
|---|---|
| NVS (Node Version Switcher) (0) | 2020.12.10 | 
| MagicMirror 설치하기 (0) | 2020.12.01 | 

