feat(plugins): inject API on window.__TAURI__ (#383)

This commit is contained in:
Lucas Fernandes Nogueira
2023-05-23 10:20:14 -07:00
committed by GitHub
parent 3c8577bc9a
commit b131bc8f7c
78 changed files with 754 additions and 337 deletions
+28 -1
View File
@@ -6,7 +6,7 @@ import { builtinModules } from "module";
import typescript from "@rollup/plugin-typescript";
import resolve from "@rollup/plugin-node-resolve";
// import terser from "@rollup/plugin-terser";
import terser from "@rollup/plugin-terser";
/**
* Create a base rollup config
@@ -15,6 +15,10 @@ import resolve from "@rollup/plugin-node-resolve";
* @returns {import('rollup').RollupOptions}
*/
export function createConfig({ input = "index.ts", pkg, external = [] }) {
const pluginJsName = pkg.name
.replace("@tauri-apps/plugin-", "")
.replace(/-./g, (x) => x[1].toUpperCase());
const iifeVarName = `__TAURI_${pluginJsName.toUpperCase()}__`;
return [
{
input,
@@ -51,5 +55,28 @@ export function createConfig({ input = "index.ts", pkg, external = [] }) {
typescript({ sourceMap: true }),
],
},
{
input,
output: {
file: "src/api-iife.js",
format: "iife",
name: iifeVarName,
// IIFE is in the format `var ${iifeVarName} = (() => {})()`
// we check if __TAURI__ exists and inject the API object
banner: "if ('__TAURI__' in window) {",
// the last `}` closes the if in the banner
footer: `Object.defineProperty(window.__TAURI__, '${pluginJsName}', { value: ${iifeVarName} }) }`,
},
// and var is not guaranteed to assign to the global `window` object so we make sure to assign it
plugins: [
resolve(),
typescript({
sourceMap: false,
declaration: false,
declarationDir: undefined,
}),
terser(),
],
},
];
}
+1
View File
@@ -39,6 +39,7 @@ impl<R: Runtime, T: Manager<R>> crate::{{ plugin_name_pascal_case }}Ext<R> for T
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("{{ plugin_name }}")
.js_init_script(include_str!("api-iife.js").to_string())
.invoke_handler(tauri::generate_handler![commands::execute])
.setup(|app, api| {
#[cfg(mobile)]