Desenvolvendo um aplicativo simples de uma maneira difícil

Olá a todos!


Há relativamente tempo, veio a mim a tarefa de aprender a escrever um trabalho, e finalmente o escrevi. Para que o bem não desapareça, decidi organizá-lo (curso) na forma de um artigo. Espero que este artigo seja útil não apenas para quem quer mergulhar no mundo do desenvolvimento da Web, mas também para aqueles que acreditam que a web moderna não é tão complicada para pagar um salário alto.


Então, o tema do curso:


Desenvolva um programa "Pesquisar". O programa deve procurar as palavras fornecidas em um arquivo de texto. As palavras são inseridas seqüencialmente no teclado. Para cada palavra, o número de ocorrências e os números de linha do texto devem ser determinados. Se a palavra especificada não estiver no arquivo, o programa deve exibir uma mensagem.

Estou desenvolvendo todo tipo de SPA e PWA há muito tempo, mas, de alguma forma, não havia como tocar na Electron . Fechando lentamente o MS Visual Studio, pensei, por que não ...


E, vamos começar com as ferramentas do desenvolvedor.




O software moderno é desenvolvido usando o ISR (IDE) - Integrated Development Environment. Tais ambientes de desenvolvimento permitem que o programador desenvolva software ( software ) de alta qualidade , passando pelos estágios de desenvolvimento, da escrita interativa do código do programa, compilação, montagem e depuração, início automático de testes e finalização com outras ferramentas de desenvolvedor convenientes e compreensíveis. Antes do advento do ISR, o desenvolvimento demorava muito tempo, mesmo nos produtos de software mais simples. Ao mesmo tempo, a qualidade do desenvolvimento também sofreu. Os SRIs destinam-se principalmente a automatizar o processo de desenvolvimento. Quanto mais complexa a tecnologia e o ambiente, mais flexível e complexa seráISR e ferramentas que ele pode implementar por si só.


. . — Visual Studio Code, Microsoft Windows, Linux macOS. «» - . , Git, , IntelliSense . : , . , , . Visual Studio Code , …



- Visual Studio Code


– PhpStorm. - Web . JetBrains IntelliJ IDEA. PhpStorm PHP, HTML JavaScript , PHP JavaScript. PhpStorm PHP 5.3, 5.4, 5.5, 5.6, 7.0, 7.1, 7.2 7.4 ( ), , , , , . SQL- .


, IntelliJ, .


"" PhpStorm , 7 .



– PhpStorm



1.


1.1


Electron — , , GitHub, HTML, CSS JavaScript. Electron Chromium Node.js , Mac, Windows Linux.


Electron 2013 Atom. 2014 . Electron , .


Chromium — , , . Chromium Google Chrome. Electron Chromium .


Node.js — , V8 ( JavaScript ), JavaScript . Node.js JavaScript - API ( C++), , , JavaScript-. Node.js , -, Node.js ( NW.js, AppJS Electron Linux, Windows macOS) (, tessel espruino). Node.js - ( ) /.


Electron Google Chrome – n- . .



Electron


Electron IPC.


IPC ( inter-process communication) — . , , IPC. , .


, IPC, :


  • ;
  • ;
  • ;
  • (RPC).

, - , . Electron', , API Node.js -, .


. , «». . .


"" . , , . , , . , , ( ) – npm (Node Package Manager), GitHub ( 2018 Microsoft).


Npm :


  • -;
  • (CLI);
  • .

(CLI), , .


, / , .
, .


1.2 /


:


  1. web Electron – ;
  2. , Electron.

() web . web .


, «»:


  • Webpack, webpack-cli, webpack-merge. Webpack – , () , , . , Webpack JavsScript-, CSS, , html- .
    Webpack — code splitting ( ). , .
  • @ babel/coreBabel.JS , javascript ES5 ES-2015+. babel/core — , .
  • @ babel/preset-env@babel/core, , , . «babel/preset-env» .browserslistrc, . .
  • babel-plugin-prismjs – babel. PrismJS , , Prism.
  • babel-loaderWebpack. babel/core .
  • copy-webpack-pluginWebpack. .
  • css-loaderWebpack. import url() import/require() (resolve) .
  • html-webpack-pluginWebpack. html index Webpack’. , , , .
  • mini-css-extract-plugin – / Webpack. .css , .
  • null-loaderWebpack. "" , .
  • Pug, pug-loader, pug-plain-loader – Pug- , Haml JavaScript Node.js . pug-loader, pug-plain-loader – Webpack, , .
  • sass-loaderWebpack. sass (Syntactically Awesome Stylesheets) – CSS, CSS . sass-loader CSS pug.
  • style-loader – css css <style> Web .
  • vue-loader, vue-template-compiler.vue, . vue-template-compiler Vue ( template) , .

, «»:


  • prismjs – Prism, , , -. -, , .
  • Vue – JavaScript Framework. Framework «». Framework Google — .
  • Vuex – , . Vuex . Vue , , . . — . , , .
  • vue-prism-editorvue prismjs. prismjs, vue .
  • electron-find – node.js electron, , .

2. «»


2.1


«» Windows. . - OC ( ) .


. Node.JS. https://nodejs.org/ru/ . Node.JS npm (Node Package Manager) (CLI).


Node.JS , , :


npm init

:


  1. ;
  2. ;
  3. ;
  4. JavaScript ;
  5. ;
  6. Git ;
  7. , , npm;
  8. ;
  9. , , npm;

JSON.



npm .


, Enter. : package.json, .


, ( PhpStorm) , JSON .


package.json
{
  "name": "stext",
  "version": "1.0.0",
  "description": " : :   «».         .     .           .      ,      ",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron .",
    "dev": "webpack --mode=development --config webpack.dev.js --progress",
    "build": "webpack --config webpack.prod.js --env.F --mode=production --progress --hide-modules",
    "pack": "electron-builder --dir",
    "dist": "electron-builder"
  },
  "build": {
    "appId": "roman.gavrilow.ru.stext",
    "icon": "app/mainicon.png",
    "win": {
      "target": [
        {
          "target": "nsis",
          "arch": [
            "x64"
          ]
        }
      ]
    }
  },
  "author": "roman@gavrilow.ru",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/preset-env": "^7.9.5",
    "babel-loader": "^8.1.0",
    "babel-plugin-prismjs": "^2.0.1",
    "copy-webpack-plugin": "^5.1.1",
    "css-loader": "^3.5.1",
    "electron": "^8.2.1",
    "electron-builder": "^22.4.1",
    "html-webpack-plugin": "^4.0.4",
    "mini-css-extract-plugin": "^0.9.0",
    "null-loader": "^3.0.0",
    "prismjs": "^1.20.0",
    "pug": "^2.0.4",
    "pug-loader": "^2.4.0",
    "pug-plain-loader": "^1.0.0",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.3",
    "vue": "^2.6.11",
    "vue-loader": "^15.9.1",
    "vue-template-compiler": "^2.6.11",
    "vuex": "^3.1.3",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11",
    "webpack-merge": "^4.2.2"
  },
  "dependencies": {
    "electron-find": "^1.0.6",
    "vue-prism-editor": "^0.5.1"
  }
}

package.json. :


"scripts"


  • "start": "electron .", Electron . , , , "main".
  • "dev": "webpack --mode=development --config webpack.dev.js --progress", . , .
  • "build": "webpack --config webpack.prod.js --env.F --mode=production --progress --hide-modules", , .
  • "pack": "electron-builder --dir", Electron «dist\» .
  • "dist": "electron-builder"Electron , .

devDependencies dependencies , . 1.2


package.json , npm install npm. node_modules , , , , …


2.2


     2.2.1 .


Electron main package.json. "main.js".


:


const { app, BrowserWindow, globalShortcut, Menu, dialog } = require('electron');

  • app — Electron .
  • BrowserWindow – render .
  • globalShortcut – .
  • Menu – .
  • Dialog – .

. , . Electron. :


main.js
const { app, BrowserWindow, globalShortcut, Menu, dialog } = require('electron');

let win;

const isMac = process.platform === 'darwin';

function createWindow () {
    //   .
    win = new BrowserWindow({
        width: 800,
        height: 600,
        center: true,
        title: '   .   ..',
        icon: 'app/mainicon.png',
        webPreferences: {
            nodeIntegration: true
        }
    });

    //   index.html .
    win.loadFile('app/index.html');

    // ,      .
    //win.webContents.openDevTools();

    //    "focus",       
    //      Ctrl + F
    win.on('focus', () => {
        globalShortcut.register('CommandOrControl+F', function () {
            if (win && win.webContents) {
                //    "on-find"   .
                win.webContents.send('on-find')
            }
        })
    });

    //    "blur",        
    //       Ctrl + F
    win.on('blur', () => {
        globalShortcut.unregister('CommandOrControl+F')
    });

}

const template = [
    {
        label: '',
        submenu: [
            {
                label: '',
                click: async () => { //          ""
                    //      
                    let files = await dialog.showOpenDialog(win,{ properties: ['openFile'] });

                    if (win && win.webContents) {
                        //    "on-files-select"      .
                        await win.webContents.send('on-files-select', files)
                    }
                }
            },

            { type: 'separator' }, //  .
            isMac ? { role: 'close' } : { role: 'quit' } //      Electron
        ]
    },
    {
        label: '',
        submenu: [
            {
                label: '',
                click: async () => { //         ""
                    if (win && win.webContents) {
                        //    "on-find"   .
                        win.webContents.send('on-find')
                    }
                }
            }
        ]
    }
];

app.whenReady().then(function(){
    createWindow();
});

app.on('will-quit', () => {
    //    .
    globalShortcut.unregisterAll()
});

const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);

Menu Menu.buildFromTemplate(template), template JSON JavaScript Object. "main.js". :


const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);


«»


     2.2.2 IPC.


, , Electron. , - render , IPC . Electron , , BrowserWindow:


win.webContents.send('on-find')
await win.webContents.send('on-files-select', files)

, «src/electron.js»


ipcRenderer.on('on-find', (e, args) => {

});

ipcRenderer.on('on-files-select', (e, args) => {

});

'on-find' – .
'on-files-select' – , , «». . , .


     2.2.3


«» Vue. -, Vue . (view), . , Vue (SPA, Single-Page Applications), .


Vue Model-View-ViewModel (MVVM) . 2005 (John Gossman), Presentation Model. , Windows Presentation Foundation, Silverlight Microsoft.


MVVM MVC , , , « ». MVC/MVP , (. Controller) Presenter. WPF Silverlight « », . , MVC, - , MVC/MVP.


Vue . «». . , , :



Vue — , , Vue .


Vue , Webpack, (entry). JavaScript «.js». «src/main.js». Web , , (bundle).


, Webpack webpack.common.js, . Webpack :


  • webpack.common.js
  • webpack.dev.js
  • webpack.prod.js

Webpack , .


Vue, vue-prism-editor, 1.2 . ( ) «».


Vue 3 : , . . . “src/app.vue”. template lang="pug", vue-loader pug , pug html . , html.


<script> . Vue , (hooks) . , , , . «» created(), . , - “src/main.js”. (ON_SELECT_FILE) , IPC, Electron. IPC “on-files-select”


ON_SELECT_FILE . created() , , , , language, . language – . , prism-editor . , text. text , prism-editor , .


     2.3


Electron , Webpack’. 2 : development (webpack.dev.js) production (webpack.prod.js). webpack.dev.js webpack.prod.js webpack.common.js. , . "webpack-merge" npm. devDependencies «package.json». , , Webpack’ (. scripts «package.json».) Webpack’ : path: path.resolve(__dirname, './app'). development production , production : + js, css , , VueJS , (bundle) Webpack’.


development :


npm run dev

«/app».



, , .


"production" :


npm run build


«/app» Webpack .


2.4 «»


Electron :


npm start

"scripts" :


"start": "electron ."

«electron .» Electron «» , "main" «package.json»



     2.4.1


«». «main.js», .


, «» «» Ctrl+F.



, .
(. .). . , , / (1/2). "<" ">" .



, , "0/0".


     2.4.2


, . , , open source npm, API Electron. dependencies «package.json» 'electron-find'. «src/electron.js». Webpak’ . () ipc 'on-find', Electron Ctrl+F «». (. main.js)


2.5 «»


, - Web , « » . Electron Chromium, , , , Google Chrome. , (main.js), Electron, «Dev Tools». (render ):


win.webContents.openDevTools();

2.6 «»


, - , , . 'devDependencies 'electron-builder. 'electron-builder — Electron « ». 'electron-builder «package.json». 64- Windows:


  "build": {
    "appId": "roman.gavrilow.ru.stext",
    "icon": "app/mainicon.png",
    "win": {
      "target": [
        {
          "target": "nsis",
          "arch": [
            "x64"
          ]
        }
      ]
    }
  },

:



, :


npm run dist

.



. :


npm run pack


«dist/win-unpacked» .



web (), Webpack «/app», . , electron-builder «» () .asar resources. tar- , . Electron .


Electron API: Node API, Node.js Web API, Chromium. API asar:


  • Node API: Electron Node API, , fs.readFile require asar , — .
  • Web API: - file:. Node API, asar , :
    let response = await this.$http.get('file:///path/to/example.asar/file.txt', parms);

«.asar» , , , original-fs, fs asar:


const originalFs = require('original-fs');
originalFs.readFileSync('/path/to/example.asar');


«» Web , , - , . – Electron (Chromium). (50 ; 180 – ),



Electron , ( Skype). , ( (IDE) — Visual Studio Code).


.


«» , , , , .


, Ctrl+F .


, - , Electron . … «» , . .


, , . , , C++ C++ QT. web , , , C++ , Web , , GET POST . , , , .


Talvez no futuro, com um certo refinamento do Chromium, possamos lançar aplicativos Electron executados em uma caixa de proteção estendida separada do processo principal já em execução do navegador Google Chrome, e precisaremos apenas iniciar apenas um processo de renderização, economizando RAM e ter o tamanho mínimo do próprio aplicativo Electron, que não incluirá mais um cromo completo.


Projeto GitHub:
https://github.com/gewisser/SText




Glossário
№ /
1(IDE).
2
3, , , , .
4()
5(Framework), ; , .
6, .
7.
8
9, .
10, .
11.
12-, HTTP- , -, HTTP-, , HTML-, , , - .
13-, — (, ), , (, ).
14, . , .
15, . , , , .
16IPC ( inter-process communication).
17, .
18, , .
19( ),
20, , , .
21WebpackWebpack .
22WebpackWebpack .
23, html- html-
24, (, )
25́, , ,
26, . , , , , .
27JSONJavaScript Object Notation — , , . JavaScript, ECMA-262 3rd Edition — December 1999.
28(hooks), .
29Vue .
30webWeb , .
31APIApplication Programming Interface — , .
32, .


All Articles