You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Sources/JavaScriptKit/Documentation.docc/Articles/Exporting-Swift-to-JavaScript.md
+90Lines changed: 90 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -162,3 +162,93 @@ export type Exports = {
162
162
}
163
163
}
164
164
```
165
+
166
+
## Using Namespaces
167
+
168
+
The `@JS` macro supports organizing your exported Swift code into namespaces using dot-separated strings. This allows you to create hierarchical structures in JavaScript that mirror your Swift code organization.
169
+
170
+
### Functions with Namespaces
171
+
172
+
You can export functions to specific namespaces by providing a namespace parameter:
The generated TypeScript declaration will reflect the namespace structure:
192
+
193
+
```typescript
194
+
declareglobal {
195
+
namespaceMyModule {
196
+
namespaceUtils {
197
+
functionnamespacedFunction(): string;
198
+
}
199
+
}
200
+
}
201
+
```
202
+
203
+
### Classes with Namespaces
204
+
205
+
For classes, you only need to specify the namespace on the top-level class declaration. All exported methods within the class will be part of that namespace:
206
+
207
+
```swift
208
+
importJavaScriptKit
209
+
210
+
@JS("__Swift.Foundation") classGreeter {
211
+
varname: String
212
+
213
+
@JSinit(name: String) {
214
+
self.name = name
215
+
}
216
+
217
+
@JSfuncgreet() -> String {
218
+
return"Hello, " + self.name + "!"
219
+
}
220
+
221
+
funcchangeName(name: String) {
222
+
self.name = name
223
+
}
224
+
}
225
+
```
226
+
227
+
In JavaScript, this class is accessible through its namespace:
228
+
229
+
```javascript
230
+
// Create instances through namespaced constructors
The generated TypeScript declaration will organize the class within its namespace:
236
+
237
+
```typescript
238
+
declareglobal {
239
+
namespace__Swift {
240
+
namespaceFoundation {
241
+
classGreeter {
242
+
constructor(name: string);
243
+
greet(): string;
244
+
}
245
+
}
246
+
}
247
+
}
248
+
249
+
exportinterfaceGreeterextendsSwiftHeapObject {
250
+
greet(): string;
251
+
}
252
+
```
253
+
254
+
Using namespaces can be preferable for projects with many global functions, as they help prevent naming collisions. Namespaces also provide intuitive hierarchies for organizing your exported Swift code, and they do not affect the code generated by `@JS` declarations without namespaces.
0 commit comments