# NPMパッケージの利用方法

このチュートリアルでは、Monacaテンプレートを使用してElectronアプリを作成します。\
アプリでは、NPMパッケージを使用してマシンのuuidを取得する方法を紹介します。

{% hint style="info" %}
NPMパッケージを使用してマシンのuuidを取得する方法はcordova-electron 3.0.0では非対応です。Deviceプラグインをご利用ください。
{% endhint %}

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

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

![](/files/-MgxsI1QiWD3yceFSSKl)

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

Cordovaプロジェクトで作業する場合、プロジェクトのルートディレクトリ内にElectron設定ファイルを作成し、 `config.xml` ファイルの設定オプション `ElectronSettingsFilePath` で作成した設定ファイルの相対パスを定義することをお勧めします。\
オプションの詳細については、[Electron's Docs - BrowserWindow Options. ](https://electronjs.org/docs/api/browser-window#new-browserwindowoptions)を参照ください。

1. Electronプラットフォームタグに `ElectronSettingsFilePath` 設定タグを作成します

   ```markup
    <platform name="electron">
        ...
        <preference name="ElectronSettingsFilePath" value="res/electron/settings.json"/>
    </platform>
   ```
2. 設定ファイルを作成し、`nodeIntegration` を `true` に設定します

   ```javascript
    {
        "browserWindow": {
            ...
            "webPreferences": {
            ...
            "nodeIntegration": true
            }
        }
    }
   ```

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

新規のターミナルを開き、プロジェクトに移動して、目的のパッケージをインストールします。このチュートリアルでは、 `node-machine-id`をインストールしてマシンのUUIDを取得します。ターミナルで `npm install node-machine-id`を実行しましょう。

{% hint style="info" %}
ターミナル機能は、有料プランから使用できます。
{% endhint %}

正常に実行された後、 `package.json`の`dependencies`プロパティに `node-machine-id`が含まれているはずです。

```javascript
{
    ...
    "dependencies": {
        ...
        "node-machine-id": "^1.1.12"
    }
}
```

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

パッケージをインストールしたら、モジュールを `require` または `import`して利用します。

次のコードの `getDeviceUUIDForElectronPlatform` 関数は、 前の手順でインストールした `node-machine-id` パッケージを `require` にて使用して、\
electronプラットフォームのマシンUUIDを取得します。その他のプラットフォームの場合は、cordovaプラグイン `cordova-plugin-device` の`device.uuid`プロパティを使用して、`ios`または`android`プラットフォームのデバイスuuidを取得します。

{% hint style="info" %}
デバイスuuidは、ブラウザプラットフォームでは使用できません。
{% endhint %}

```javascript
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();
```

参考ページ:

* [Electronアプリのビルド](/products_guide/monaca_ide/build/electron.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ja.docs.monaca.io/tutorials/cordova_electron/use_npm_package.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
