LoginSignup
4
5

More than 5 years have passed since last update.

electron-packager の `ignore` をたぶんほぼ完璧に指定する

Posted at

Electron のパッケージを作成する際に、起動に必要のないmoduleを除外する必要があるけど、↓以下の記事で紹介されているような問題があって、単純に package.jsondevDependencies に指定されているものを除外するだけでは devDependency が依存している module が除外できなくなる。

npm v3 で Electron のパッケージサイズが大きくなる - Qiita

なので以下のような感じで頑張る(試してないけど↑で紹介されている --global-style を使ったほうが楽だと思う)

使うもの

  • shelljs
  • lodash

コード

require('shelljs/global');
const difference = require('lodash/difference');


const requireFiles = [
  'bundle.js',
  'index.html',
  'main.js',
  'node_modules',
  'package.json',
];

const installedNodeModules = ls('node_modules').map(e => e);
const productionInfo = JSON.parse(
  exec('npm list --production --depth=1000 --json', { silent: true }).stdout
);

function extractDependencies(info) {
  if (!info.dependencies) { return []; }
  return Object.keys(info.dependencies).reduce((pkgs, name) => {
    const childDeps = extractDependencies(info.dependencies[name]);
    return pkgs.concat(name, childDeps);
  }, []);
}

const productionDependencies = extractDependencies(productionInfo);
const devDependencies = difference(installedNodeModules, productionDependencies);

// これを electron-packager の ignore に指定する
const ignoreFiles = difference(ls('./').map(e => e), requireFiles)
  .concat(devDependencies.map(name => `/node_modules/${name}(/|$)`));

なにやってんの

requireFiles は、Electronアプリを起動するのに最低限のファイル。bundle.js は browserify とか webpack で作ってるファイル名に適宜変える。あとでカレントディレクトリにあるファイルとの差分を取って、必要ないやつを指定する。

installedNodeModulesnpm install されてるやつを列挙してる。

productionInfo は、dependencies に指定してる module を、それが依存しているのも含めて取り出してる。たぶん 1000 も深く潜れば大丈夫だろうという指定をしている。

extractDependencies は、productionInfo が持ってる dependencies を潜ってって、必要なやつの名前を取り出して productionDependencies に入れてる。

devDependencies はさっき取り出した、すべての module と必要な module の差分を取ってる。

ignoreFiles はカレントディレクトリで必要ないやつと必要ない node_modules を結合してる。


終わり

4
5
0

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
4
5