@cloudflare/vite-plugin 0.0.0-fd5a45520 → 0.0.0-fd8c0c44c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,48 +1,8 @@
1
1
  # `@cloudflare/vite-plugin`
2
2
 
3
- [Intro](#intro) | [Quick start](#quick-start) | [Tutorial](#tutorial) | [API](#api) | [Cloudflare environments](#cloudflare-environments) | [Migrating from `wrangler dev`](#migrating-from-wrangler-dev)
4
-
5
- ## Intro
6
-
7
- The Cloudflare Vite plugin enables a full-featured integration between Vite and the Workers runtime.
3
+ The Cloudflare Vite plugin enables a full-featured integration between [Vite](https://vite.dev/) and the [Workers runtime](https://developers.cloudflare.com/workers/runtime-apis/).
8
4
  Your Worker code runs inside [workerd](https://github.com/cloudflare/workerd), matching the production behavior as closely as possible and providing confidence as you develop and deploy your applications.
9
5
 
10
- ### Features
11
-
12
- - Provides direct access to Workers runtime APIs and bindings
13
- - Supports Workers Assets, enabling you to build static sites, SPAs, and full-stack applications
14
- - Leverages Vite's hot module replacement for consistently fast updates
15
- - Supports `vite preview` for previewing your build output in the Workers runtime prior to deployment
16
-
17
- ## Quick start
18
-
19
- ### Start with a basic `package.json`
20
-
21
- ```json
22
- {
23
- "name": "cloudflare-vite-quick-start",
24
- "private": true,
25
- "version": "0.0.0",
26
- "type": "module",
27
- "scripts": {
28
- "dev": "vite",
29
- "build": "vite build",
30
- "preview": "vite preview"
31
- }
32
- }
33
- ```
34
-
35
- > [!NOTE]
36
- > Ensure that you include `"type": "module"` in order to use ES modules by default.
37
-
38
- ### Install the dependencies
39
-
40
- ```sh
41
- npm install vite @cloudflare/vite-plugin wrangler --save-dev
42
- ```
43
-
44
- ### Create your Vite config file and include the Cloudflare plugin
45
-
46
6
  ```ts
47
7
  // vite.config.ts
48
8
 
@@ -54,431 +14,22 @@ export default defineConfig({
54
14
  });
55
15
  ```
56
16
 
57
- ### Create your Worker config file
58
-
59
- ```toml
60
- # wrangler.toml
61
-
62
- name = "cloudflare-vite-quick-start"
63
- compatibility_date = "2024-12-30"
64
- main = "./src/index.ts"
65
- ```
66
-
67
- ### Create your Worker entry file
68
-
69
- ```ts
70
- // src/index.ts
71
-
72
- export default {
73
- fetch() {
74
- return new Response(`Running in ${navigator.userAgent}!`);
75
- },
76
- };
77
- ```
78
-
79
- You can now develop (`npm run dev`), build (`npm run build`), preview (`npm run preview`), and deploy (`npm exec wrangler deploy`) your application.
80
-
81
- ## Tutorial
82
-
83
- In this tutorial, you will create a React SPA that can be deployed as a Worker with Workers Assets.
84
- Then, you will add an API Worker that can be accessed from the front-end code.
85
- You will develop, build, and preview the application using Vite before finally deploying to Cloudflare.
86
-
87
- ### Set up and configure the React SPA
88
-
89
- #### Scaffold a Vite project
90
-
91
- Start by creating a React TypeScript project with Vite.
92
-
93
- ```sh
94
- npm create vite@latest cloudflare-vite-tutorial -- --template react-ts
95
- ```
96
-
97
- Open the `cloudflare-vite-tutorial` directory in your editor of choice.
98
-
99
- #### Add the Cloudflare dependencies
100
-
101
- ```sh
102
- npm install @cloudflare/vite-plugin wrangler --save-dev
103
- ```
104
-
105
- #### Add the plugin to your Vite config
106
-
107
- ```ts
108
- // vite.config.ts
109
-
110
- import { defineConfig } from "vite";
111
- import react from "@vitejs/plugin-react";
112
- import { cloudflare } from "@cloudflare/vite-plugin";
113
-
114
- export default defineConfig({
115
- plugins: [react(), cloudflare()],
116
- });
117
- ```
118
-
119
- #### Create your Worker config file
120
-
121
- ```toml
122
- # wrangler.toml
123
-
124
- name = "cloudflare-vite-tutorial"
125
- compatibility_date = "2024-12-30"
126
- assets = { not_found_handling = "single-page-application" }
127
- ```
128
-
129
- The [`not_found_handling`](https://developers.cloudflare.com/workers/static-assets/routing/#not_found_handling--404-page--single-page-application--none) value has been set to `single-page-application`.
130
- This means that all not found requests will serve the `index.html` file.
131
- With the Cloudflare plugin, the `assets` routing configuration is used in place of Vite's default behavior.
132
- This ensures that your application's routing works the same way while developing as it does when deployed to production.
133
-
134
- Note that the [`directory`](https://developers.cloudflare.com/workers/static-assets/binding/#directory) field is not used when configuring assets with Vite.
135
- The `directory` in the output configuration will automatically point to the client build output.
136
-
137
- > [!NOTE]
138
- > When using the Cloudflare Vite plugin, the Worker config (for example, `wrangler.toml`) that you provide is the input configuration file.
139
- > A separate output `wrangler.json` file is created when you run `vite build`.
140
- > This output file is a snapshot of your configuration at the time of the build and is modified to reference your build artifacts.
141
- > It is the configuration that is used for preview and deployment.
142
-
143
- #### Run the development server
144
-
145
- Run `npm run dev` to verify that your application is working as expected.
146
-
147
- For a purely front-end application, you could now build (`npm run build`), preview (`npm run preview`), and deploy (`npm exec wrangler deploy`) your application.
148
- However, this tutorial will show you how to go a step further and add an API Worker.
149
-
150
- ### Add an API Worker
151
-
152
- #### Configure TypeScript for your Worker code
153
-
154
- ```sh
155
- npm install @cloudflare/workers-types --save-dev
156
- ```
157
-
158
- ```jsonc
159
- // tsconfig.worker.json
160
-
161
- {
162
- "extends": "./tsconfig.node.json",
163
- "compilerOptions": {
164
- "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.worker.tsbuildinfo",
165
- "types": ["@cloudflare/workers-types/2023-07-01", "vite/client"],
166
- },
167
- "include": ["api"],
168
- }
169
- ```
170
-
171
- ```jsonc
172
- // tsconfig.json
173
-
174
- {
175
- "files": [],
176
- "references": [
177
- { "path": "./tsconfig.app.json" },
178
- { "path": "./tsconfig.node.json" },
179
- { "path": "./tsconfig.worker.json" },
180
- ],
181
- }
182
- ```
183
-
184
- #### Add to your Worker configuration
185
-
186
- ```toml
187
- # wrangler.toml
188
-
189
- name = "cloudflare-vite-tutorial"
190
- compatibility_date = "2024-12-30"
191
- assets = { not_found_handling = "single-page-application", binding = "ASSETS" }
192
- main = "./api/index.ts"
193
- ```
194
-
195
- The assets `binding` defined here will allow you to access the assets functionality from your Worker.
196
-
197
- #### Add your API Worker
198
-
199
- ```ts
200
- // api/index.ts
201
-
202
- interface Env {
203
- ASSETS: Fetcher;
204
- }
205
-
206
- export default {
207
- fetch(request, env) {
208
- const url = new URL(request.url);
209
-
210
- if (url.pathname.startsWith("/api/")) {
211
- return Response.json({
212
- name: "Cloudflare",
213
- });
214
- }
215
-
216
- return env.ASSETS.fetch(request);
217
- },
218
- } satisfies ExportedHandler<Env>;
219
- ```
220
-
221
- The Worker above will be invoked for any request not matching a static asset.
222
- It returns a JSON response if the `pathname` starts with `/api/` and otherwise passes the incoming request through to the assets binding.
223
- This means that for paths that do not start with `/api/`, the `not_found_handling` behavior defined in the Worker config will be evaluated and the `index.html` file will be returned, enabling SPA navigations.
224
-
225
- #### Call the API from the client
17
+ ## Documentation
226
18
 
227
- Edit `src/App.tsx` so that it includes an additional button that calls the API and sets some state.
228
- Replace the file contents with the following code:
19
+ Full documentation can be found [here](https://developers.cloudflare.com/workers/vite-plugin/).
229
20
 
230
- ```tsx
231
- // src/App.tsx
21
+ ## Features
232
22
 
233
- import { useState } from "react";
234
- import reactLogo from "./assets/react.svg";
235
- import viteLogo from "/vite.svg";
236
- import "./App.css";
237
-
238
- function App() {
239
- const [count, setCount] = useState(0);
240
- const [name, setName] = useState("unknown");
241
-
242
- return (
243
- <>
244
- <div>
245
- <a href="https://vite.dev" target="_blank">
246
- <img src={viteLogo} className="logo" alt="Vite logo" />
247
- </a>
248
- <a href="https://react.dev" target="_blank">
249
- <img src={reactLogo} className="logo react" alt="React logo" />
250
- </a>
251
- </div>
252
- <h1>Vite + React</h1>
253
- <div className="card">
254
- <button
255
- onClick={() => setCount((count) => count + 1)}
256
- aria-label="increment"
257
- >
258
- count is {count}
259
- </button>
260
- <p>
261
- Edit <code>src/App.tsx</code> and save to test HMR
262
- </p>
263
- </div>
264
- <div className="card">
265
- <button
266
- onClick={() => {
267
- fetch("/api/")
268
- .then((res) => res.json() as Promise<{ name: string }>)
269
- .then((data) => setName(data.name));
270
- }}
271
- aria-label="get name"
272
- >
273
- Name from API is: {name}
274
- </button>
275
- <p>
276
- Edit <code>api/index.ts</code> to change the name
277
- </p>
278
- </div>
279
- <p className="read-the-docs">
280
- Click on the Vite and React logos to learn more
281
- </p>
282
- </>
283
- );
284
- }
285
-
286
- export default App;
287
- ```
288
-
289
- Now, if you click the button, it will display 'Name from API is: Cloudflare'.
290
-
291
- Increment the counter to update the application state in the browser.
292
- Next, edit `api/index.ts` by changing the `name` it returns to `'Cloudflare Workers'`.
293
- If you click the button again, it will display the new `name` while preserving the previously set counter value.
294
- With Vite and the Cloudflare plugin, you can iterate on the client and server parts of your app quickly without losing UI state between edits.
295
-
296
- #### Build your application
297
-
298
- Run `npm run build` to build your application.
299
-
300
- If you inspect the `dist` directory, you will see that it contains two subdirectories: `client` and `cloudflare-vite-tutorial`.
301
- The `cloudflare-vite-tutorial` directory contains your Worker code and the output `wrangler.json` configuration.
302
-
303
- #### Preview your application
304
-
305
- Run `npm run preview` to validate that your application runs as expected.
306
- This command will run your build output locally in the Workers runtime, closely matching its behaviour in production.
307
-
308
- #### Deploy to Cloudflare
309
-
310
- Run `npm exec wrangler deploy` to deploy your application to Cloudflare.
311
- This command will automatically use the output `wrangler.json` that was included in the build output.
312
-
313
- ### Next steps
314
-
315
- In this tutorial, we created an SPA that could be deployed as a Worker with Workers Assets.
316
- We then added an API Worker that could be accessed from the front-end code and deployed to Cloudflare.
317
- Possible next steps include:
318
-
319
- - Adding a binding to another Cloudflare service such as a [KV namespace](https://developers.cloudflare.com/kv/) or [D1 database](https://developers.cloudflare.com/d1/)
320
- - Expanding the API to include additional routes
321
- - Using a library, such as [tRPC](https://trpc.io/) or [Hono](https://hono.dev/), in your API Worker
322
-
323
- ## API
324
-
325
- ### `cloudflare`
326
-
327
- The `cloudflare` plugin should be included in the Vite `plugins` array:
328
-
329
- ```ts
330
- // vite.config.ts
331
-
332
- import { defineConfig } from "vite";
333
- import { cloudflare } from "@cloudflare/vite-plugin";
334
-
335
- export default defineConfig({
336
- plugins: [cloudflare()],
337
- });
338
- ```
339
-
340
- It accepts an optional `PluginConfig` parameter.
341
-
342
- ### `interface PluginConfig`
343
-
344
- - `configPath?: string`
345
-
346
- An optional path to your Worker config file.
347
- By default, a `wrangler.toml`, `wrangler.json`, or `wrangler.jsonc` file in the root of your application will be used as the Worker config.
348
-
349
- - `viteEnvironment?: { name?: string }`
350
-
351
- Optional Vite environment options.
352
- By default, the environment name is the Worker name with `-` characters replaced with `_`.
353
- Setting the name here will override this.
354
-
355
- - `persistState?: boolean | { path: string }`
356
-
357
- An optional override for state persistence.
358
- By default, state is persisted to `.wrangler/state` in a `v3` subdirectory.
359
- A custom `path` can be provided or, alternatively, persistence can be disabled by setting the value to `false`.
360
-
361
- - `auxiliaryWorkers?: Array<AuxiliaryWorkerConfig>`
362
-
363
- An optional array of auxiliary workers.
364
- You can use [service bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) to call auxiliary workers from your main (entry) Worker.
365
- All requests are routed through your entry Worker.
366
- During the build, each Worker is output to a separate subdirectory of `dist`.
367
-
368
- > [!NOTE]
369
- > When running `wrangler deploy`, only your main (entry) Worker will be deployed.
370
- > If using multiple Workers, each must be deployed individually.
371
- > You can inspect the `dist` directory and then run `wrangler deploy -c path-to-worker-output-config` for each.
372
-
373
- ### `interface AuxiliaryWorkerConfig`
374
-
375
- - `configPath: string`
376
-
377
- A required path to your Worker config file.
378
-
379
- - `viteEnvironment?: { name?: string }`
380
-
381
- Optional Vite environment options.
382
- By default, the environment name is the Worker name with `-` characters replaced with `_`.
383
- Setting the name here will override this.
384
-
385
- ## Cloudflare environments
386
-
387
- A Worker config file may contain configuration for multiple [Cloudflare environments](https://developers.cloudflare.com/workers/wrangler/environments/).
388
- With the Cloudflare Vite plugin, you select a Cloudflare environment at dev or build time by providing the `CLOUDFLARE_ENV` environment variable.
389
- Consider the following example `wrangler.toml` file:
390
-
391
- ```toml
392
- # wrangler.toml
393
-
394
- name = "my-worker"
395
- compatibility_date = "2024-12-30"
396
- main = "./src/index.ts"
397
-
398
- vars = { MY_VAR = "Top-level var" }
399
-
400
- [env.staging]
401
- vars = { MY_VAR = "Staging var" }
402
-
403
- [env.production]
404
- vars = { MY_VAR = "Production var" }
405
- ```
406
-
407
- If you run `CLOUDFLARE_ENV=production vite build` then the output `wrangler.json` file generated by the build will be a flattened configuration for the 'production' Cloudflare environment.
408
- This combines [top-level only](https://developers.cloudflare.com/workers/wrangler/configuration/#top-level-only-keys), [inheritable](https://developers.cloudflare.com/workers/wrangler/configuration/#inheritable-keys), and [non-inheritable](https://developers.cloudflare.com/workers/wrangler/configuration/#non-inheritable-keys) keys.
409
- The value of `MY_VAR` will therefore be `'Production var'`.
410
- The name of the Worker will be `'my-worker-production'`.
411
- This is because the environment name is automatically appended to the top-level Worker name.
412
-
413
- > [!NOTE]
414
- > The default Vite environment name for a Worker is always the top-level Worker name.
415
- > This enables you to reference the Worker consistently in your Vite config when using multiple Cloudflare environments.
416
-
417
- Cloudflare environments can also be used in development.
418
- For example, you could run `CLOUDFLARE_ENV=development vite dev`.
419
- It is common to use the default top-level environment as the development environment and then add additional environments as necessary.
420
-
421
- > [!NOTE]
422
- > Running `vite dev` or `vite build` without providing `CLOUDFLARE_ENV` will use the default top-level Cloudflare environment.
423
- > The value of `MY_VAR` will therefore be `'Top-level var'`.
424
- > As Cloudflare environments are applied at dev and build time, specifying `CLOUDFLARE_ENV` when running `vite preview` or `wrangler deploy` will have no effect.
425
-
426
- ### Combining Cloudflare environments and Vite modes
427
-
428
- You may wish to combine the concepts of [Cloudflare environments](https://developers.cloudflare.com/workers/wrangler/environments/) and [Vite modes](https://vite.dev/guide/env-and-mode.html#modes).
429
- With this approach, the Vite mode can be used to select the Cloudflare environment and a single method can be used to determine environment specific configuration and code.
430
- Consider again the previous example:
431
-
432
- ```toml
433
- # wrangler.toml
434
-
435
- name = "my-worker"
436
- compatibility_date = "2024-12-30"
437
- main = "./src/index.ts"
438
-
439
- vars = { MY_VAR = "Top-level var" }
440
-
441
- [env.staging]
442
- vars = { MY_VAR = "Staging var" }
443
-
444
- [env.production]
445
- vars = { MY_VAR = "Production var" }
446
- ```
447
-
448
- Next, provide `.env.staging` and `.env.production` files:
449
-
450
- ```sh
451
- # .env.staging
452
-
453
- CLOUDFLARE_ENV=staging
454
- ```
455
-
456
- ```sh
457
- # .env.production
458
-
459
- CLOUDFLARE_ENV=production
460
- ```
461
-
462
- By default, `vite build` uses the 'production' Vite mode.
463
- Vite will therefore load the `.env.production` file to get the environment variables that are used in the build.
464
- Since the `.env.production` file contains `CLOUDFLARE_ENV=production`, the Cloudflare Vite plugin will select the 'production' Cloudflare environment.
465
- The value of `MY_VAR` will therefore be `'Production var'`.
466
- If you run `vite build --mode staging` then the 'staging' Vite mode will be used and the 'staging' Cloudflare environment will be selected.
467
- The value of `MY_VAR` will therefore be `'Staging var'`.
468
-
469
- ## Migrating from `wrangler dev`
470
-
471
- Migrating from `wrangler dev` is a simple process and you can follow the instructions in the [Quick start](#quick-start) to get started.
472
- There are a few key differences to highlight:
473
-
474
- ### Input and output Worker config files
475
-
476
- In the Vite integration, your Worker config file (for example, `wrangler.toml`) is the input configuration and a separate output configuration is created as part of the build.
477
- This output file is a snapshot of your configuration at the time of the build and is modified to reference your build artifacts.
478
- It is the configuration that is used for preview and deployment.
23
+ - Uses the Vite [Environment API](https://vite.dev/guide/api-environment) to integrate Vite with the Workers runtime
24
+ - Provides direct access to [Workers runtime APIs](https://developers.cloudflare.com/workers/runtime-apis/) and [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/)
25
+ - Builds your front-end assets for deployment to Cloudflare, enabling you to build static sites, SPAs, and full-stack applications
26
+ - Official support for [React Router v7](https://reactrouter.com/) with server-side rendering
27
+ - Leverages Vite's hot module replacement for consistently fast updates
28
+ - Supports `vite preview` for previewing your build output in the Workers runtime prior to deployment
479
29
 
480
- ### Redundant fields in the Wrangler config file
30
+ ## Use cases
481
31
 
482
- There are various options in the Worker config file that are ignored when using Vite, as they are either no longer applicable or are replaced by Vite equivalents.
483
- If these options are provided, then warnings will be printed to the console with suggestions for how to proceed.
484
- Examples where the Vite configuration should be used instead include `alias` and `define`.
32
+ - React Router v7 (support for more full-stack frameworks is coming soon)
33
+ - Static sites, such as single-page applications, with or without an integrated backend API
34
+ - Standalone Workers
35
+ - Multi-Worker applications