microsoft / microsoft/node-api-dotnet

A possible vite plugin to make this work with electron.

オープン
#397 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
C#
スター
783
フォーク
80
PR マージ指標
30日以内にマージされた PR はありません

説明

After days of research I wrote a plugin to make this cool node-api-dotnet works with electron. Hope it can help people later.

  1. Create a vite plugin
import fs from "fs";
import path from "path";

interface ElectronNodeApiDotNetOptions {
    // The path to `node_modules/node-api-dotnet
    nodeModulePath: string,

    // The path to all generated files and assemblies
    csprojOutputPath: string,
}

export default (options: ElectronNodeApiDotNetOptions) => {
    const name = "electron-node-api-dotnet";

    let assemblyName = "Microsoft.JavaScript.NodeApi";
    let assemblyRoot = path.normalize(options.csprojOutputPath)

    const transformInitJs = (code: string) => {

        // Create require to dynamic require .node files.
        code = `
                    import path from "path";
                    import { createRequire } from 'module';
                    const require = createRequire(import.meta.url);
                    const bundleRoot = ${JSON.stringify(options.nodeModulePath)};
                ` + code

        // Since we use import above, we also need to replace the export style.
        // https://github.com/rollup/plugins/issues/1121
        code = code.replace(
            "module.exports = initialize",
            "export default initialize"
        )

        // Get the dotnet assembly name, preventing upstream change.
        const regex = /const assemblyName\s*=\s*['"`](.*?)['"`];/;
        const match = code.match(regex);
        if (match) {
            assemblyName = match[1];
            console.log(`[${name}] Using assembly name: ${assemblyName}`);
        } else {
            console.error(
                `[${name}] Cannot match assembly name, plugin may not work!`
            );
        }

        // Transform dynamic assemblyName require to a static one
        // Also transform the relative paths to be prefixed with provided bundle root.
        code = code.replace(
            /require\(`\.\/(.+?)\/\$\{assemblyName\}\.node`\)/g,
            "require(path.join(bundleRoot, `./$1/" + assemblyName + ".node`))"
        );

        // Transform the default case.
        code = code.replace(
            "nativeHost = require(__dirname + `/${rid}/${assemblyName}.node`)",
            "nativeHost = require(path.join(bundleRoot, `./${rid}/${assemblyName}.node`))"
        )

        // Transform the path for managed host.
        code = code.replace(
            "const managedHostPath = __dirname + `/${targetFramework}/${assemblyName}.DotNetHost.dll`",
            "const managedHostPath = path.join(bundleRoot, `./${targetFramework}/${assemblyName}.DotNetHost.dll`)"
        )

        return code;
    }

    const transformAssemblyJs = (code: string, filePath: string) => {

        // Instead of use import.meta.url
        code = code.replace(
            "import { fileURLToPath } from 'node:url';", ""
        )
        
        // Use the absolute path, because these files will be rollup 
        // to one single file (for example main.js)
        code = code.replace(
            "const __filename = fileURLToPath(import.meta.url)",
            `const __filename = ${JSON.stringify(filePath)}`
        )

        return code
    }

    return {
        name,
        resolveId(source: string, importer: string | undefined, options: any) {
            return null;
        },
        transform(code: string, id: string) {
            const normId = path.normalize(id)
            if (id.endsWith("node_modules/node-api-dotnet/init.js")) {
                return transformInitJs(code)
            } else if (normId.startsWith(assemblyRoot)) {
                return transformAssemblyJs(code, normId)
            }
            return code;
        },
        load(id: string) {
            if (id.endsWith(`${assemblyName}.node`)) {
                // Treat .node files as empty string, otherwise there'll be error because binary are
                // not valid js files.
                return ``;
            }
            return null;
        },
        generateBundle(options: any, bundle: any) {
            // bundle whatever way you want
        },
    };
};

  1. Include it in vite config, or nuxt config, if you like. Remember to exclude files from commonjs plugin.
import commonjs from '@rollup/plugin-commonjs'
import resolve from '@rollup/plugin-node-resolve'
import electronNodeDotNetApi from './rollup/electron-node-api-dotnet'

...

vite: {
  plugins: [
    resolve(),
    commonjs({
      exclude: [
        "node_modules/node-api-dotnet/**"
      ]
    }),
    electronNodeDotNetApi({
      nodeModulePath: path.join(projectRootDir, 'node_modules/node-api-dotnet'),
      csprojOutputPath: csharpOutputDir
    }),
  ]
}

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

提案されている Vite plugin のコードと Vite 設定例をレビューし、node-api-dotnet/init.js および生成された assembly ファイルに対する transforms も確認します。まず、このプロジェクトが Electron/Vite 統合を維持する意向があるか、またどのファイルやテストを追加すべきかを明確にしてください。issue では受け入れ基準が定義されていないため、完了には合意された受け入れ基準が必要です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
csharp, electron, node.js, typescript, vite
領域
build-system, desktop, tooling
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
30/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。