LoginSignup
54

More than 5 years have passed since last update.

Electron+Aceを使って50行ぐらいで作る構文ハイライト付きJavaScriptエディタ

Last updated at Posted at 2015-08-16

ElectronにAceを組み合わせると、僅かなコードで構文ハイライト付きエディタアプリが作れるので、参考までサンプルを実装してみました。

※ (2016.05.24 修正) Electron v1.x 向けに記述を改めました。 Electron v0.x 系 では動作しません。

スクリーンショット 2016-05-24 14.22.24.png

アプリ画面にjsファイルをD&Dすると編集できます。保存機能は未実装です。

準備

前提条件として必要なものはnpmだけです。
最初にまだelectronを入れてなかったら、インストールします。

$ npm install electron-prebuild -g

次にプロジェクトフォルダを作ります

$ mkdir test-project
$ cd test-project
$ npm init -y

Aceを入れる

$ npm install ace-min-noconflict --save

index.js を作る

以下のソースをindex.jsという名前でプロジェクトフォルダに保存します。
内容はElectronのサンプルコードほぼそのままです。

index.js
const electron = require('electron');
const {app} = electron;
const {BrowserWindow} = electron;
let win;

function createWindow() {
  win = new BrowserWindow({width: 800, height: 600});
  win.loadURL(`file://${__dirname}/index.html`);
  win.on('closed', () => { win = null; });
}
app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (win === null) createWindow();
});

index.htmlを作る

以下のソースをindex.htmlという名前でプロジェクトフォルダに保存します。

index.html
<!DOCTYPE html>
<html>
<head>
  <style>
    * {padding:0;margin:0;box-sizing:border-box;}
    html, body, #editor {width:100%;height:100%;}
  </style>
  <script>
    require('ace-min-noconflict');
    require('ace-min-noconflict/mode-javascript');

    var editor;
    window.addEventListener('DOMContentLoaded',function() { 
      editor = ace.edit("editor");
      editor.getSession().setMode('ace/mode/javascript');
      editor.$blockScrolling = Infinity; // ワーニングに対処
      if(process.platform == 'darwin') { // Ctrl+Pが効かない問題に対処
        editor.commands.bindKey("Ctrl-P", "golineup"); 
      }
      document.body.addEventListener('dragover', function(e) { 
        e.preventDefault(); 
      });
      document.body.addEventListener('drop', function(e) { 
        e.preventDefault(); 
        if(e.dataTransfer.files[0]) {
          var file = e.dataTransfer.files[0].path;
          if(/\.js$/.test(file)) { 
            openFile(file); 
          }
        }
      });
    });

    function openFile(file) {
      require('fs').readFile(file,'utf8', function(err,data) {
        editor.setValue(data,-1);
      });
    }    
  </script>
</head>
<body><div id="editor"></div></body>
</html>

完成

以上で完成です。プロジェクトディレクトリをelectronに食わせて起動します。

$ electron .

制限

ace-min-conflict パッケージに worker-javascript.js が含まれないため、構文チェックは実行されません(コンソールに worker-javascript.js の読み込み失敗エラーが表示されます)。

おわりに

サンプルなのであくまで簡単に、ということでファイルの保存機能は付けていませんが、

あたりを使うと簡単に実装できます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
54