NPMパッケージの利用方法
このチュートリアルでは、Monacaテンプレートを使用してElectronアプリを作成します。
アプリでは、NPMパッケージを使用してマシンのuuidを取得する方法を紹介します。
NPMパッケージを使用してマシンのuuidを取得する方法はcordova-electron 3.0.0では非対応です。Deviceプラグインをご利用ください。
まず、空のテンプレートを作成しましょう。 Monacaダッシュボードから、
新しいプロジェクトを作る → サンプル アプリケーション
.
次に、テンプレートリストから Electron Blank
を選択し、「プロジェクト名」と「説明」を入力して、「プロジェクトを作成」をクリックします。
Cordovaプロジェクトで作業する場合、プロジェクトのルートディレクトリ内にElectron設定ファイルを作成し、
config.xml
ファイルの設定オプション ElectronSettingsFilePath
で作成した設定ファイルの相対パスを定義することをお勧めします。
オプションの詳細については、Electron's Docs - BrowserWindow Options. を参照ください。- 1.Electronプラットフォームタグに
ElectronSettingsFilePath
設定タグを作成します<platform name="electron">...<preference name="ElectronSettingsFilePath" value="res/electron/settings.json"/></platform> - 2.設定ファイルを作成し、
nodeIntegration
をtrue
に設定します{"browserWindow": {..."webPreferences": {..."nodeIntegration": true}}}
新規のターミナルを開き、プロジェクトに移動して、目的のパッケージをインストールします。このチュートリアルでは、
node-machine-id
をインストールしてマシンのUUIDを取得します。ターミナルで npm install node-machine-id
を実行しましょう。ターミナル機能は、有料プランから使用できます。
正常に実行された後、
package.json
のdependencies
プロパティに node-machine-id
が含まれているはずです。{
...
"dependencies": {
...
"node-machine-id": "^1.1.12"
}
}
パッケージをインストールしたら、モジュールを
require
または import
して利用します。次のコードの
getDeviceUUIDForElectronPlatform
関数は、 前の手順でインストールした node-machine-id
パッケージを require
にて使用して、
electronプラットフォームのマシンUUIDを取得します。その他のプラットフォームの場合は、cordovaプラグイン cordova-plugin-device
のdevice.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();
参考ページ:
最終更新 8mo ago