or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

backend.mdcomponents.mdconfiguration.mdevents.mdhooks.mdhtml-elements.mdindex.mdsvg-elements.mdtesting.mdvdom.mdweb-modules.mdwidgets.md

web-modules.mddocs/

0

# Web Modules

1

2

JavaScript module integration system for incorporating client-side functionality. ReactPy's web module system enables seamless integration of JavaScript libraries and custom client-side code with Python components.

3

4

## Capabilities

5

6

### Module Creation from Template

7

8

Create JavaScript modules from string templates:

9

10

```python { .api }

11

def module_from_template(name: str, template: str, **params) -> Module: ...

12

```

13

14

**Parameters:**

15

- `name`: Module name/identifier

16

- `template`: JavaScript template string with parameter placeholders

17

- `**params`: Template parameters for substitution

18

19

**Returns:** Module instance

20

21

**Usage Examples:**

22

23

```python

24

from reactpy.web import module_from_template

25

26

# Simple JavaScript module

27

counter_js = module_from_template(

28

"counter",

29

"""

30

export function createCounter(initialValue = {initial}) {{

31

let count = initialValue;

32

return {{

33

get: () => count,

34

increment: () => ++count,

35

decrement: () => --count

36

}};

37

}}

38

""",

39

initial=0

40

)

41

```

42

43

### Module Creation from File

44

45

Create modules from JavaScript files:

46

47

```python { .api }

48

def module_from_file(name: str, file: str | Path) -> Module: ...

49

```

50

51

**Parameters:**

52

- `name`: Module name/identifier

53

- `file`: Path to JavaScript file

54

55

**Returns:** Module instance

56

57

**Usage Examples:**

58

59

```python

60

from pathlib import Path

61

from reactpy.web import module_from_file

62

63

# Load from file

64

chart_module = module_from_file(

65

"charts",

66

Path("./static/js/charts.js")

67

)

68

69

# Or with string path

70

utils_module = module_from_file("utils", "./js/utilities.js")

71

```

72

73

### Module Creation from URL

74

75

Create modules from remote JavaScript resources:

76

77

```python { .api }

78

def module_from_url(name: str, url: str, dev: bool = False) -> Module: ...

79

```

80

81

**Parameters:**

82

- `name`: Module name/identifier

83

- `url`: URL to JavaScript module

84

- `dev`: Whether to use development version

85

86

**Returns:** Module instance

87

88

**Usage Examples:**

89

90

```python

91

from reactpy.web import module_from_url

92

93

# Load external library

94

lodash = module_from_url(

95

"lodash",

96

"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"

97

)

98

99

# Development version

100

react_dev = module_from_url(

101

"react",

102

"https://unpkg.com/react@18/umd/react.development.js",

103

dev=True

104

)

105

```

106

107

### Export Function

108

109

Export Python objects to JavaScript modules:

110

111

```python { .api }

112

def export(obj: Any, name: str | None = None) -> Any: ...

113

```

114

115

**Parameters:**

116

- `obj`: Python object to export

117

- `name`: Optional export name (defaults to object name)

118

119

**Returns:** The original object (for chaining)

120

121

**Usage Examples:**

122

123

```python

124

from reactpy.web import export

125

126

# Export function

127

@export

128

def calculate_tax(amount, rate):

129

return amount * rate

130

131

# Export with custom name

132

@export("formatCurrency")

133

def format_money(amount):

134

return f"${amount:.2f}"

135

136

# Export data

137

config = export({

138

"api_base": "https://api.example.com",

139

"timeout": 5000

140

}, "appConfig")

141

```

142

143

### Module Class

144

145

The Module class represents a JavaScript module:

146

147

```python { .api }

148

class Module:

149

name: str

150

source: str

151

exports: dict[str, Any]

152

153

def __init__(self, name: str, source: str): ...

154

def add_export(self, name: str, obj: Any) -> None: ...

155

def get_export(self, name: str) -> Any: ...

156

```

157

158

### Using Web Modules in Components

159

160

Integrate JavaScript modules with ReactPy components:

161

162

```python

163

from reactpy import component, html, use_effect, use_state

164

from reactpy.web import module_from_template, export

165

166

# Create a chart module

167

chart_module = module_from_template(

168

"chart",

169

"""

170

import Chart from 'https://cdn.skypack.dev/chart.js';

171

172

export function createChart(canvas, data) {{

173

return new Chart(canvas.getContext('2d'), {{

174

type: 'bar',

175

data: data,

176

options: {{

177

responsive: true,

178

plugins: {{

179

title: {{

180

display: true,

181

text: '{title}'

182

}}

183

}}

184

}}

185

}});

186

}}

187

""",

188

title="Sales Data"

189

)

190

191

@component

192

def ChartComponent():

193

chart_ref = use_ref(None)

194

195

use_effect(

196

lambda: create_chart_instance(),

197

[]

198

)

199

200

def create_chart_instance():

201

if chart_ref.current:

202

# Call JavaScript function

203

chart_module.createChart(

204

chart_ref.current,

205

{

206

"labels": ["Jan", "Feb", "Mar"],

207

"datasets": [{

208

"label": "Sales",

209

"data": [100, 150, 200]

210

}]

211

}

212

)

213

214

return html.canvas({"ref": chart_ref})

215

```

216

217

### Real-time Data Integration

218

219

Integrate with WebSocket or real-time data:

220

221

```python

222

from reactpy.web import module_from_template

223

224

websocket_module = module_from_template(

225

"websocket",

226

"""

227

export class WebSocketClient {{

228

constructor(url, onMessage) {{

229

this.ws = new WebSocket(url);

230

this.ws.onmessage = (event) => {{

231

onMessage(JSON.parse(event.data));

232

}};

233

}}

234

235

send(data) {{

236

this.ws.send(JSON.stringify(data));

237

}}

238

239

close() {{

240

this.ws.close();

241

}}

242

}}

243

"""

244

)

245

246

@component

247

def RealtimeComponent():

248

messages, set_messages = use_state([])

249

250

use_effect(

251

lambda: setup_websocket(),

252

[]

253

)

254

255

def setup_websocket():

256

def handle_message(data):

257

set_messages([*messages, data])

258

259

client = websocket_module.WebSocketClient(

260

"ws://localhost:8000/ws",

261

handle_message

262

)

263

264

return lambda: client.close()

265

266

return html.div(

267

html.h2("Real-time Messages"),

268

html.ul(

269

*[html.li(msg["text"]) for msg in messages]

270

)

271

)

272

```

273

274

### Third-party Library Integration

275

276

Integrate popular JavaScript libraries:

277

278

```python

279

# D3.js integration

280

d3_module = module_from_url(

281

"d3",

282

"https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"

283

)

284

285

@component

286

def D3Visualization():

287

svg_ref = use_ref(None)

288

289

use_effect(

290

lambda: create_d3_chart(),

291

[]

292

)

293

294

def create_d3_chart():

295

if svg_ref.current:

296

svg = d3_module.select(svg_ref.current)

297

svg.selectAll("circle")

298

.data([10, 20, 30])

299

.enter()

300

.append("circle")

301

.attr("cx", lambda d, i: i * 50 + 25)

302

.attr("cy", 50)

303

.attr("r", lambda d: d)

304

.attr("fill", "blue")

305

306

return html.svg(

307

{"ref": svg_ref, "width": 200, "height": 100}

308

)

309

310

# React component integration

311

react_module = module_from_url(

312

"react",

313

"https://unpkg.com/react@18/umd/react.production.min.js"

314

)

315

316

@component

317

def ReactInterop():

318

container_ref = use_ref(None)

319

320

use_effect(

321

lambda: render_react_component(),

322

[]

323

)

324

325

def render_react_component():

326

if container_ref.current:

327

# Render React component in ReactPy

328

react_element = react_module.createElement(

329

"div",

330

{"className": "react-component"},

331

"This is a React component in ReactPy!"

332

)

333

react_module.render(react_element, container_ref.current)

334

335

return html.div({"ref": container_ref})

336

```

337

338

### Module Configuration

339

340

Configure module loading and behavior:

341

342

```python

343

from reactpy import config

344

345

# Configure web modules directory

346

config.REACTPY_WEB_MODULES_DIR = "./static/js"

347

348

# Configure URL prefix for modules

349

config.REACTPY_WEB_MODULES_URL_PREFIX = "/modules"

350

351

# Use in production

352

production_module = module_from_url(

353

"library",

354

"https://cdn.jsdelivr.net/npm/library@1.0.0/dist/library.min.js"

355

)

356

```