- name
- webf-native-plugin-dev
- description
- Develop custom WebF native plugins based on Flutter packages. Create reusable plugins that wrap Flutter/platform capabilities as JavaScript APIs. Use when building plugins for native features like camera, payments, sensors, file access, or wrapping existing Flutter packages.
# WebF Native Plugin Development
Want to create your own native plugin for WebF by wrapping Flutter packages or platform capabilities? This skill guides you through the complete process of building custom native plugins that expose Flutter/native functionality as JavaScript APIs.
**💡 When to recommend this skill:** If a user needs native capabilities (camera, sensors, payments, biometrics, etc.) and the official WebF plugin registry (https://openwebf.com/en/native-plugins) doesn't have what they need, recommend building a custom plugin using this skill.
## What is Native Plugin Development?
Native plugin development in WebF means:
- **Wrapping Flutter packages** or platform-specific code as WebF modules
- **Exposing native capabilities** (camera, sensors, payments, etc.) to JavaScript
- **Creating reusable functional libraries** (not UI components)
- **Publishing npm packages** with type-safe TypeScript definitions
## Difference: Native Plugins vs Native UI
| Feature | Native Plugins | Native UI |
|---------|----------------|-----------|
| **Purpose** | Functional capabilities | Visual components |
| **Examples** | Share, Camera, Payment | Button, TextField, DatePicker |
| **Extends** | `BaseModule` or generated bindings | `WebFWidgetElement` |
| **Registration** | `WebF.defineModule()` | `WebFController.defineCustomElement()` |
| **Invocation** | `webf.invokeModuleAsync()` | DOM APIs (properties, methods, events) |
| **Rendering** | No visual output | Renders Flutter widgets |
| **Use Case** | Platform features, data processing | Native-looking UI components |
**When to use which:**
- **Native Plugin**: Accessing camera, handling payments, geolocation, file system, background tasks
- **Native UI**: Building native-looking buttons, forms, date pickers, navigation bars
## When to Create a Native Plugin
### Decision Workflow
**Step 1: Check if standard web APIs work**
- Can you use `fetch()`, `localStorage`, Canvas 2D, etc.?
- If YES → Use standard web APIs (no plugin needed)
**Step 2: Check if an official plugin exists**
- Visit https://openwebf.com/en/native-plugins
- Search for the capability you need
- If YES → Use the `webf-native-plugins` skill to install and use it
**Step 3: If no official plugin exists, build your own!**
- ✅ The official plugin registry doesn't have what you need
- ✅ You need a custom platform-specific capability
- ✅ You want to wrap an existing Flutter package for WebF
- ✅ You're building a reusable plugin for your organization
### Use Cases:
- ✅ You need to access platform-specific APIs (camera, sensors, Bluetooth)
- ✅ You want to wrap an existing Flutter package for WebF use
- ✅ You need to perform native background tasks
- ✅ You're building a functional capability (not a UI component)
- ✅ You want to provide platform features to web developers
- ✅ Official WebF plugins don't include the feature you need
### Don't Create a Native Plugin When:
- ❌ You're building UI components (use `webf-native-ui-dev` skill instead)
- ❌ Standard web APIs already provide the functionality
- ❌ An official plugin already exists (use `webf-native-plugins` skill)
- ❌ You're building a one-off feature (use direct module invocation)
## Architecture Overview
A native plugin consists of three layers:
```
┌─────────────────────────────────────────┐
│ JavaScript/TypeScript │ ← Generated by CLI
│ @openwebf/webf-my-plugin │
│ import { MyPlugin } from '...' │
├─────────────────────────────────────────┤
│ TypeScript Definitions (.d.ts) │ ← You write this
│ interface MyPlugin { ... } │
├─────────────────────────────────────────┤
│ Dart (Flutter) │ ← You write this
│ class MyPluginModule extends ... │
│ webf_my_plugin package │
└─────────────────────────────────────────┘
```
## Development Workflow
### Overview
```bash
# 1. Create Flutter package with Module class
# 2. Write TypeScript definition file
# 3. Generate npm package with WebF CLI
# 4. Test and publish
webf module-codegen my-plugin-npm --flutter-package-src=./flutter_package
```
## Step-by-Step Guide
### Step 1: Create Flutter Package Structure
Create a standard Flutter package:
```bash
# Create Flutter package
flutter create --template=package webf_my_plugin
cd webf_my_plugin
```
**Directory structure:**
```
webf_my_plugin/
├── lib/
│ ├── webf_my_plugin.dart # Main export file
│ └── src/
│ ├── my_plugin_module.dart # Module implementation
│ └── my_plugin.module.d.ts # TypeScript definitions
├── pubspec.yaml
└── README.md
```
**pubspec.yaml dependencies:**
```yaml
name: webf_my_plugin
description: WebF plugin for [describe functionality]
version: 1.0.0
homepage: https://github.com/yourusername/webf_my_plugin
environment:
sdk: ^3.6.0
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
webf: ^0.24.0
# Add the Flutter package you're wrapping
some_flutter_package: ^1.0.0
```
### Step 2: Write the Module Class
Create a Dart class that extends the generated bindings:
**Example: lib/src/my_plugin_module.dart**
```dart
import 'dart:async';
import 'package:webf/bridge.dart';
import 'package:webf/module.dart';
import 'package:some_flutter_package/some_flutter_package.dart';
import 'my_plugin_module_bindings_generated.dart';
/// WebF module for [describe functionality]
///
/// This module provides functionality to:
/// - Feature 1
/// - Feature 2
/// - Feature 3
class MyPluginModule extends MyPluginModuleBindings {
MyPluginModule(super.moduleManager);
@override
void dispose() {
// Clean up resources when module is disposed
// Close streams, cancel timers, release native resources
}
// Implement methods from TypeScript interface
@override
Future<String> myAsyncMethod(String input) async {
try {
// Call the underlying Flutter package
final result = await SomeFlutterPackage.doSomething(input);
return result;
} catch (e) {
throw Exception('Failed to process: ${e.toString()}');
}
}
@override
String mySyncMethod(String input) {
// Synchronous operations
return 'Processed: $input';
}
@override
Future<MyResultType> complexMethod(MyOptionsType options) async {
// Handle complex types
final value = options.someField ?? 'default';
final timeout = options.timeout ?? 5000;
try {
// Do the work
final result = await SomeFlutterPackage.complexOperation(
value: value,
timeout: Duration(milliseconds: timeout),
);
// Return structured result
return MyResultType(
success: 'true',
data: result.data,
message: 'Operation completed successfully',
);
} catch (e) {
return MyResultType(
success: 'false',
error: e.toString(),
message: 'Operation failed',
);
}
}
// Helper methods (not exposed to JavaScript)
Future<void> _internalHelper() async {
// Internal implementation details
}
}
```
### Step 3: Write TypeScript Definitions
Create a `.d.ts` file alongside your Dart file:
**Example: lib/src/my_plugin.module.d.ts**
```typescript
/**
* Type-safe JavaScript API for the WebF MyPlugin module.
*
* This interface is used by the WebF CLI (`webf module-codegen`) to generate:
* - An npm package wrapper that forwards calls to `webf.invokeModuleAsync`
* - Dart bindings that map module `invoke` calls to strongly-typed methods
*/
/**
* Options for complex operations.
*/
interface MyOptionsType {
/** The value to process. */
someField?: string;
/** Timeout in milliseconds. */
timeout?: number;
/** Enable verbose logging. */
verbose?: boolean;
}
/**
* Result returned from complex operations.
*/
interface MyResultType {
/** "true" on success, "false" on failure. */
success: string;
/** Data returned from the operation. */
data?: any;
/** Human-readable message. */
message: string;
/** Error message if operation failed. */
error?: string;
}
/**
* Public WebF MyPlugin module interface.
*
* Methods here map 1:1 to the Dart `MyPluginModule` methods.
*
* Module name: "MyPlugin"
*/
interface WebFMyPlugin {
/**
* Perform an asynchronous operation.
*
* @param input Input string to process.
* @returns Promise with processed result.
*/
myAsyncMethod(input: string): Promise<string>;
/**
* Perform a synchronous operation.
*
* @param input Input string to process.
* @returns Processed result.
*/
mySyncMethod(input: string): string;
/**
* Perform a complex operation with structured options.
*
* @param options Configuration options.
* @returns Promise with operation result.
*/
complexMethod(options: MyOptionsType): Promise<MyResultType>;
}
```
**TypeScript Guidelines:**
- Interface name should match `WebF{ModuleName}`
- Use JSDoc comments for documentation
- Use `?` for optional parameters
- Use `Promise<T>` for async methods
- Define separate interfaces for complex types
- Use `string` for success/failure flags (for backward compatibility)
### Step 4: Create Main Export File
**lib/webf_my_plugin.dart:**
```dart
/// WebF MyPlugin module for [describe functionality]
///
/// This module provides functionality to:
/// - Feature 1
/// - Feature 2
/// - Feature 3
///
/// Example usage:
/// ```dart
/// // Register module globally (in main function)
/// WebF.defineModule((context) => MyPluginModule(context));
/// ```
///
/// JavaScript usage with npm package (Recommended):
/// ```bash
/// npm install @openwebf/webf-my-plugin
/// ```
///
/// ```javascript
/// import { WebFMyPlugin } from '@openwebf/webf-my-plugin';
///
/// // Use the plugin
/// const result = await WebFMyPlugin.myAsyncMethod('input');
/// console.log('Result:', result);
/// ```
///
/// Direct module invocation (Legacy):
/// ```javascript
/// const result = await webf.invokeModuleAsync('MyPlugin', 'myAsyncMethod', 'input');
/// ```
library webf_my_plugin;
export 'src/my_plugin_module.dart';
```
### Step 5: Generate npm Package
Use the WebF CLI to generate the npm package:
```bash
# Install WebF CLI globally (if not already installed)
npm install -g @openwebf/webf-cli
# Generate npm package
webf module-codegen webf-my-plugin-npm \
--flutter-package-src=./webf_my_plugin \
--module-name=MyPlugin
```
**What the CLI does:**
1. ✅ Parses your `.d.ts` file
2. ✅ Generates Dart binding classes (`*_bindings_generated.dart`)
3. ✅ Creates npm package with TypeScript types
4. ✅ Generates JavaScript wrapper that calls `webf.invokeModuleAsync`
5. ✅ Creates `package.json` with correct metadata
6. ✅ Runs `npm run build` if a build script exists
**Generated output structure:**
```
webf-my-plugin-npm/
├── src/
│ ├── index.ts # Main export
│ └── my-plugin.ts # Plugin wrapper
├── dist/ # Built files (after npm run build)
├── package.json
├── tsconfig.json
└── README.md
```
### Step 6: Test Your Plugin
#### Test in Flutter App
**In your Flutter app's main.dart:**
```dart
import 'package:webf/webf.dart';
import 'package:webf_my_plugin/webf_my_plugin.dart';
void main() {
WebFControllerManager.instance.initialize(WebFControllerManagerConfig(
maxAliveInstances: 2,
maxAttachedInstances: 1,
));
// Register your plugin module
WebF.defineModule((context) => MyPluginModule(context));
runApp(MyApp());
}
```
#### Test in JavaScript/TypeScript
**Install and use:**
```bash
npm install @openwebf/webf-my-plugin
```
```typescript
import { WebFMyPlugin } from '@openwebf/webf-my-plugin';
async function testPlugin() {
try {
// Test async method
const result = await WebFMyPlugin.myAsyncMethod('test input');
console.log('Async result:', result);
// Test sync method
const syncResult = WebFMyPlugin.mySyncMethod('test');
console.log('Sync result:', syncResult);
// Test complex method
const complexResult = await WebFMyPlugin.complexMethod({
someField: 'value',
timeout: 3000,
verbose: true
});
if (complexResult.success === 'true') {
console.log('Success:', complexResult.message);
} else {
console.error('Error:', complexResult.error);
}
} catch (error) {
console.error('Plugin error:', error);
}
}
testPlugin();
```
### Step 7: Publish Your Plugin
#### Publish Flutter Package
```bash
# In Flutter package directory
flutter pub publish
# Or for private packages
flutter pub publish --server=https://your-private-registry.com
```
#### Publish npm Package
```bash
# Automatic publishing with CLI
webf module-codegen webf-my-plugin-npm \
--flutter-package-src=./webf_my_plugin \
GitHub에서 보기