Monaca Docs
検索
K

NPMパッケージの利用方法

このチュートリアルでは、Monacaテンプレートを使用してElectronアプリを作成します。 アプリでは、NPMパッケージを使用してマシンのuuidを取得する方法を紹介します。
NPMパッケージを使用してマシンのuuidを取得する方法はcordova-electron 3.0.0では非対応です。Deviceプラグインをご利用ください。

ステップ 1: Electron プロジェクトの作成

まず、空のテンプレートを作成しましょう。 Monacaダッシュボードから、新しいプロジェクトを作る → サンプル アプリケーション. 次に、テンプレートリストから Electron Blank を選択し、「プロジェクト名」と「説明」を入力して、「プロジェクトを作成」をクリックします。

ステップ 2: Nodeの利用を有効にする

Cordovaプロジェクトで作業する場合、プロジェクトのルートディレクトリ内にElectron設定ファイルを作成し、 config.xml ファイルの設定オプション ElectronSettingsFilePath で作成した設定ファイルの相対パスを定義することをお勧めします。 オプションの詳細については、Electron's Docs - BrowserWindow Options. を参照ください。
  1. 1.
    Electronプラットフォームタグに ElectronSettingsFilePath 設定タグを作成します
    <platform name="electron">
    ...
    <preference name="ElectronSettingsFilePath" value="res/electron/settings.json"/>
    </platform>
  2. 2.
    設定ファイルを作成し、nodeIntegrationtrue に設定します
    {
    "browserWindow": {
    ...
    "webPreferences": {
    ...
    "nodeIntegration": true
    }
    }
    }

ステップ 3: NPM パッケージのインストール

新規のターミナルを開き、プロジェクトに移動して、目的のパッケージをインストールします。このチュートリアルでは、 node-machine-idをインストールしてマシンのUUIDを取得します。ターミナルで npm install node-machine-idを実行しましょう。
ターミナル機能は、有料プランから使用できます。
正常に実行された後、 package.jsondependenciesプロパティに node-machine-idが含まれているはずです。
{
...
"dependencies": {
...
"node-machine-id": "^1.1.12"
}
}

ステップ 4: NPM パッケージの利用

パッケージをインストールしたら、モジュールを require または importして利用します。
次のコードの getDeviceUUIDForElectronPlatform 関数は、 前の手順でインストールした node-machine-id パッケージを require にて使用して、 electronプラットフォームのマシンUUIDを取得します。その他のプラットフォームの場合は、cordovaプラグイン cordova-plugin-devicedevice.uuidプロパティを使用して、iosまたはandroidプラットフォームのデバイスuuidを取得します。
デバイスuuidは、ブラウザプラットフォームでは使用できません。
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
console.log('device ready');
this.getDeviceUUID();
},
getDeviceUUIDForElectronPlatform: function() {
try {
const machineIdSync = require('node-machine-id').machineIdSync;
return machineIdSync({original: true});
} catch (error) {
console.error(error);
return 'Could not get machine id';
}
},
getDeviceUUID: function() {
const platformId = window.cordova.platformId;
const deviceInfo = document.getElementById('device-info');
let uuid = null;
if (platformId.includes('electron')) {
// get uuid from npm package for electron platform
uuid = this.getDeviceUUIDForElectronPlatform();
} else if (device && device.uuid && ['ios', 'android'].indexOf(platformId) >= 0) {
// get uuid from cordova-plugin-device
uuid = device.uuid;
} else {
// other platforms such as browser, ...
uuid = `The ${platformId} platform is not supported.`;
}
if (uuid) deviceInfo.innerHTML = `Device UUID: ${uuid}`;
}
};
app.initialize();
参考ページ: