Create a Capacitor Electron Plugin
Create or open a Capacitor V3 compatible plugin in your editor of choice.
Create a folder named
electron
in the root of this plugin, with a sub-folder ofsrc
in it.Create a ts file in the above
src
folder namedindex.ts
and either paste in the following example code of the@capacitor/dialog
plugin and edit away, or create your own from scratch:import { dialog } from 'electron' import type { DialogPlugin, AlertOptions, PromptOptions, PromptResult, ConfirmOptions, ConfirmResult,} from '../../src/definitions'; export class Dialog implements DialogPlugin { async alert(options: AlertOptions): Promise<void> { await dialog.showMessageBox({message: options.message + ' --- electron'}); } async prompt(options: PromptOptions): Promise<PromptResult> { const val = window.prompt(options.message, options.inputText || ''); return { value: val !== null ? val : '', cancelled: val === null, }; } async confirm(options: ConfirmOptions): Promise<ConfirmResult> { const val = window.confirm(options.message); return { value: val, }; }}
Create a
.gitignore
file in theelectron
folder with the following:dist
Create a
.npmignore
file in theelectron
folder with the following:src
Create a
rollup.config.js
file in theelectron
folder with the following:export default { input: 'electron/build/electron/src/index.js', output: [ { file: 'electron/dist/plugin.js', format: 'cjs', sourcemap: true, inlineDynamicImports: true, }, ], external: ['@capacitor/core'],};
Create a
tsconfig.json
file in theelectron
folder with the following:{ "compilerOptions": { "allowSyntheticDefaultImports": true, "declaration": true, "experimentalDecorators": true, "noEmitHelpers": true, "importHelpers": true, "lib": ["dom", "es2020"], "module": "commonjs", "noImplicitAny": true, "noUnusedLocals": true, "noUnusedParameters": true, "outDir": "build", "sourceMap": true, "strict": false, "target": "ES2017" }, "include": ["src/**/*"]}
Modify the main
package.json
in the root directory, add a property to thecapacitor
object so it reflects the following (android and ios shown for example only):"capacitor": { "ios": { "src": "ios" }, "android": { "src": "android" }, "electron": { "src": "electron" }},
Modify the main
package.json
in the root directory, add an entry into thefiles
array of the following:electron/
Modify the main
package.json
in the root directory, add an entry into thescripts
object of the following:"build-electron": "tsc --project electron/tsconfig.json && rollup -c electron/rollup.config.js && rimraf ./electron/build",
Modify the main
package.json
in the root directory, edit thebuild
entry in thescripts
object to be the following:"build": "npm run clean && npm run docgen && tsc && rollup -c rollup.config.js && npm run build-electron",
Run the
build
npm script to build your plugin.Release it to NPM then use in your capacitor apps as any other native plugin like android or ios. (dont forget to use
npx cap sync/copy/update/open @capacitor-community/electron
)