@wrdagency/react-islands 1.0.5 → 2.0.1

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,7 +1,110 @@
1
- ## React Islands
1
+ # React Islands
2
2
 
3
3
  Created by Kyle Cooper at [WRD.agency](https://webresultsdirect.com)
4
4
 
5
- React Islands is a way of introducing React into static pages. We developed React Islands as a way of introducing React-based interactivity sprinkled into places on WordPress sites (rendered via PHP).
5
+ React Islands is a way of introducing pockets of React into otherwise static pages, with an option for build-type rendering to help with layout shift. We developed React Islands as a way of introducing React-based interactivity sprinkled into places on WordPress sites (rendered via PHP).
6
6
 
7
- The ReactIslandsWebpackPlugin automatically creates statically rendered mark-up for each Webpack entry point. This is rendered to a HTML file at build time which can then be hydrated using the `createIsland`.
7
+ ## Example Setup
8
+
9
+ Create your island. Here we use an existing component and use our Islands directory to only setup the islands and not for worrying about functionality.
10
+
11
+ ```
12
+ // ./islands/my-component.tsx
13
+ import MyComponent from "./components";
14
+ import { createIsland } from "@wrdagency/react-islands";
15
+
16
+ export const myComponentIsland = createIsland(MyComponent, {
17
+ name: "my-component",
18
+ });
19
+ ```
20
+
21
+ ```
22
+ // ./islands/index.ts
23
+ export * from "./my-component";
24
+ ```
25
+
26
+ On the client you can then render each of those islands. They'll automatically hook into the DOM where the selector is matched (similar to a portal) to create an island of reactivity.
27
+
28
+ ```
29
+ // index.ts
30
+ import * as islands from "./islands";
31
+ import { hydrateIslands } from "@wrdagency/react-islands";
32
+
33
+ hydrateIslands( islands );
34
+
35
+ ```
36
+
37
+ Create a pre-render script. You can configure your build tool to use this as a seperate entrypoint.
38
+
39
+ ```
40
+ // prerender.ts
41
+
42
+ import path from "node:path";
43
+ import { fileURLToPath } from "node:url";
44
+ import * as islands from "./islands";
45
+ import { prerenderIslands } from "@wrdagency/react-islands/server";
46
+
47
+ const __filename = fileURLToPath(import.meta.url);
48
+ const __dirname = path.dirname(__filename);
49
+ const outDir = path.resolve(__dirname, "ssg");
50
+
51
+ prerenderIslands({ islands, outDir });
52
+ ```
53
+
54
+ For our example we're using Vite. We'll build our prerendering script.
55
+
56
+ ```
57
+ npx vite build --ssr ./src/prerender.tsx --outDir ./dist
58
+ ```
59
+
60
+ And then we can run that compiled script. It'll create all of our statically rendered islands and put them into the `outDir` we specified.
61
+
62
+ ```
63
+ node ./dist/prerender.js
64
+ ```
65
+
66
+ For convenience we'd recommend setting up a script in your `package.json` for this like so:
67
+
68
+ ```
69
+ "scripts": {
70
+ "prerender": "npx vite build --ssr ./src/prerender.tsx --outDir ./dist && node ./dist/prerender.js",
71
+ },
72
+ ```
73
+
74
+ ## API
75
+
76
+ ### `createIsland`
77
+
78
+ `(component: React.FC, options: IslandOpts) => Island`
79
+
80
+ Creates an island.
81
+
82
+ #### `IslandOpts`
83
+
84
+ | Options | Type | Default | Description |
85
+ | ------------ | -------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
86
+ | name | string | Required | The name of the island. Used for the default selector and the filename of pre-rendering. |
87
+ | selector | string? | [data-hydrate="{{NAME}}"] | The query selector to match for the islands root. |
88
+ | multiple | boolean? | false | If enabled, the island will by instantiated for every element that matches the selector, not just the first. |
89
+ | keepChildren | boolean? | false | If enabled, the children props of the island component will be set to the raw HTML of the existing node's children. Experimental. |
90
+
91
+ ### `withProps`
92
+
93
+ `<T>(component: React.FC<T>, props: Partial<T>) => React.FC<T>`
94
+
95
+ Creates a version of your React component with props already set. Useful for creating multiple islands with variants of the same component.
96
+
97
+ ### `isServer`
98
+
99
+ `() => boolean`
100
+
101
+ Checks if the current environment is the server. Useful for disabled certain features not available during the prerender step.
102
+
103
+ ### `prerenderIslands`
104
+
105
+ `(options: PrerenderIslandsOpts) => Promise<void>`
106
+
107
+ | Option | Type | Description |
108
+ | ------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
109
+ | islands | Record<string, Island> | The islands the pre-render. The key of the record is not used, it's just useful to accept a record if we're using `import * as Islands`. |
110
+ | ourDir | string | Path of the directory to output the static HTML to. This directory will be emptied before pre-rendering begins. |
package/bin/index.js ADDED
@@ -0,0 +1,411 @@
1
+ #!/usr/bin/env node
2
+ import fs, { readFileSync } from 'fs';
3
+ import yoctoSpinner from 'yocto-spinner';
4
+ import commonjsPlugin from '@rollup/plugin-commonjs';
5
+ import resolvePlugin from '@rollup/plugin-node-resolve';
6
+ import replacePlugin from '@rollup/plugin-replace';
7
+ import terserPlugin from '@rollup/plugin-terser';
8
+ import typescriptPlugin from '@rollup/plugin-typescript';
9
+ import path from 'path';
10
+ import { rollup } from 'rollup';
11
+ import { typescriptPaths } from 'rollup-plugin-typescript-paths';
12
+ import { exec } from 'child_process';
13
+ import { promisify } from 'util';
14
+ import commandLineArgs from 'command-line-args';
15
+ import commandLineUsage from 'command-line-usage';
16
+
17
+ function createGlobalObject(namespace) {
18
+ return namespace
19
+ .split(".")
20
+ .filter(Boolean)
21
+ .map((_, index, levels) => {
22
+ const path = "window." + levels.slice(0, index + 1).join(".");
23
+ return `${path} = ${path} || {}`;
24
+ })
25
+ .join(";\n");
26
+ }
27
+ function importPackage(packageName) {
28
+ return `import * as ${packageNameToProperty(packageName)} from "${packageName}";\n`;
29
+ }
30
+ function importAndGlobalisePackage(packageName, globalName) {
31
+ let str = "";
32
+ str += importPackage(packageName);
33
+ str += `${globalName} = ${packageNameToProperty(packageName)};\n`;
34
+ return str;
35
+ }
36
+ function packageNameToProperty(packageName) {
37
+ return packageName
38
+ .replace(/^@/, "")
39
+ .replace(/\//g, "_")
40
+ .replace(/[-_](.)/g, (_, c) => c.toUpperCase())
41
+ .replace(/^[a-z]/, (c) => c.toUpperCase());
42
+ }
43
+ function renderComponentToFile(filename, component) {
44
+ return `var server = require('react-dom/server');
45
+ var fs = require('node:fs/promises');
46
+ var path = require('node:path');
47
+ const html = server.renderToString( module.exports.component( {} ) );
48
+ const file = path.resolve(__dirname, '${filename}');
49
+ fs.writeFile(file, html, { flag: "w+" });`;
50
+ }
51
+
52
+ const normalizeOptions = (options) => {
53
+ return {
54
+ name: options.name,
55
+ input: options.input,
56
+ output: options.output || "./dist/",
57
+ minify: normalizeBoolean(options.minify, true),
58
+ ssg: normalizeBoolean(options.ssg, true),
59
+ jsx: options.jsx || "react-jsx",
60
+ typescript: normalizeBoolean(options.ssg, false),
61
+ common: normalizeCommonOption(options.common || [
62
+ "react",
63
+ "react-dom/client",
64
+ "@wrdagency/react-islands",
65
+ ]),
66
+ };
67
+ };
68
+ const normalizeBoolean = (value, fallback) => {
69
+ if (value === false) {
70
+ return false;
71
+ }
72
+ else if (value === true) {
73
+ return true;
74
+ }
75
+ else {
76
+ return fallback;
77
+ }
78
+ };
79
+ const normalizeCommonOption = (share = [""]) => {
80
+ if (Array.isArray(share)) {
81
+ return share.reduce((record, packageName) => ({
82
+ ...record,
83
+ [packageName]: "Islands._Common." + packageNameToProperty(packageName),
84
+ }), {});
85
+ }
86
+ else {
87
+ return share;
88
+ }
89
+ };
90
+
91
+ const execPromise = promisify(exec);
92
+ const consoleExecute = async (command) => {
93
+ try {
94
+ const { stdout, stderr } = await execPromise(command);
95
+ if (stdout) {
96
+ console.log(stdout);
97
+ }
98
+ if (stderr) {
99
+ console.error(stderr);
100
+ }
101
+ return stdout;
102
+ }
103
+ catch (e) {
104
+ console.error(e);
105
+ throw e;
106
+ }
107
+ };
108
+
109
+ function runScriptAfterBuildPlugin(opts) {
110
+ const { deleteAfterRunning = false } = opts;
111
+ return {
112
+ name: "rollup-plugin-run-script-after-builder",
113
+ writeBundle(outputOptions, bundle) {
114
+ const outputDir = outputOptions.dir
115
+ ? outputOptions.dir
116
+ : path.dirname(outputOptions.file || "");
117
+ for (const [fileName, chunkInfo] of Object.entries(bundle)) {
118
+ const filePath = path.resolve(outputDir, fileName);
119
+ if (chunkInfo.type !== "chunk" || !chunkInfo.isEntry) {
120
+ return;
121
+ }
122
+ if (!filePath && !filePath.endsWith("js")) {
123
+ return;
124
+ }
125
+ if (!fs.existsSync(filePath)) {
126
+ return;
127
+ }
128
+ consoleExecute(`node ${filePath}`).then(() => {
129
+ if (deleteAfterRunning) {
130
+ fs.unlinkSync(filePath);
131
+ }
132
+ });
133
+ }
134
+ },
135
+ };
136
+ }
137
+
138
+ function virtualizeDependencyPlugin(opts) {
139
+ const { dependencies, namespace = "" } = opts;
140
+ const VIRTUAL_MODULE_ID = "\0virtual-entry";
141
+ return {
142
+ name: "rollup-plugin-virtualize-dependency",
143
+ resolveId(source) {
144
+ if (source === "virtual-entry")
145
+ return VIRTUAL_MODULE_ID;
146
+ return null;
147
+ },
148
+ load(id) {
149
+ if (id !== VIRTUAL_MODULE_ID) {
150
+ return null;
151
+ }
152
+ let str = createGlobalObject(namespace) + ";\n";
153
+ for (const [dependency, name] of Object.entries(dependencies)) {
154
+ str += importAndGlobalisePackage(dependency, name);
155
+ }
156
+ return str;
157
+ },
158
+ };
159
+ }
160
+
161
+ function createRollupConfigs(options) {
162
+ const normalized = normalizeOptions(options);
163
+ const { name, input, output, minify, ssg, jsx, typescript, common } = normalized;
164
+ const configs = [];
165
+ const createRollupConfig = (opts) => {
166
+ const { active = true, name: mainName = `Islands.${name}`, subName, format, globals = {}, prefix, suffix, plugins = [], } = opts;
167
+ if (!active) {
168
+ return null;
169
+ }
170
+ return {
171
+ input,
172
+ external: Object.keys(globals),
173
+ jsx,
174
+ output: {
175
+ name: mainName,
176
+ globals,
177
+ format,
178
+ entryFileNames: `[name]/${subName}`,
179
+ dir: output,
180
+ banner: prefix && ((chunk) => prefix(chunk.name)),
181
+ footer: suffix && ((chunk) => suffix(chunk.name)),
182
+ },
183
+ plugins: [
184
+ resolvePlugin({
185
+ extensions: [
186
+ ".cjs",
187
+ ".mjs",
188
+ ".js",
189
+ ".json",
190
+ ".node",
191
+ ".jsx",
192
+ ".ts",
193
+ ".tsx",
194
+ ],
195
+ }),
196
+ commonjsPlugin(),
197
+ replacePlugin({
198
+ preventAssignment: true,
199
+ "process.env.NODE_ENV": JSON.stringify("production"),
200
+ }),
201
+ minify && terserPlugin(),
202
+ typescript &&
203
+ typescriptPlugin({
204
+ jsx,
205
+ }),
206
+ typescript && typescriptPaths(),
207
+ ...plugins,
208
+ ],
209
+ };
210
+ };
211
+ configs.push(createRollupConfig({
212
+ active: true,
213
+ subName: "client.js",
214
+ format: "iife",
215
+ globals: common,
216
+ suffix: (name) => `\nwindow.Islands['${name}']?.render('${name}')`,
217
+ }));
218
+ configs.push(createRollupConfig({
219
+ active: ssg,
220
+ subName: "server.cjs",
221
+ format: "cjs",
222
+ suffix: () => renderComponentToFile("ssg.html"),
223
+ plugins: [
224
+ runScriptAfterBuildPlugin({
225
+ deleteAfterRunning: true,
226
+ }),
227
+ ],
228
+ }));
229
+ return configs.filter(isRollupOptions);
230
+ }
231
+ function createCommonConfig(options) {
232
+ const normalized = normalizeOptions(options);
233
+ const { output, minify, jsx, common } = normalized;
234
+ return {
235
+ input: "virtual-entry",
236
+ jsx,
237
+ output: {
238
+ name: "Islands._Common",
239
+ file: path.resolve(output, "common.js"),
240
+ format: "iife",
241
+ },
242
+ plugins: [
243
+ replacePlugin({
244
+ preventAssignment: true,
245
+ "process.env.NODE_ENV": JSON.stringify("production"),
246
+ }),
247
+ virtualizeDependencyPlugin({
248
+ dependencies: common,
249
+ namespace: "Islands._Common",
250
+ }),
251
+ resolvePlugin(),
252
+ commonjsPlugin(),
253
+ minify && terserPlugin(),
254
+ ],
255
+ };
256
+ }
257
+ function isRollupOptions(config) {
258
+ return config !== null;
259
+ }
260
+ async function runRollup(inputOptions, outputOptions) {
261
+ let bundle;
262
+ let buildFailed = false;
263
+ try {
264
+ bundle = await rollup(inputOptions);
265
+ await bundle.write(outputOptions);
266
+ }
267
+ catch (error) {
268
+ buildFailed = true;
269
+ console.error(error);
270
+ }
271
+ if (bundle) {
272
+ await bundle.close();
273
+ }
274
+ return !buildFailed;
275
+ }
276
+
277
+ class Command {
278
+ args;
279
+ callback;
280
+ description;
281
+ constructor(options) {
282
+ let { args, callback, description } = options;
283
+ args.push({
284
+ name: "help",
285
+ alias: "h",
286
+ type: Boolean,
287
+ // @ts-ignore
288
+ description: "Display this usage guide.",
289
+ });
290
+ this.args = args;
291
+ this.callback = callback;
292
+ this.description = description;
293
+ }
294
+ run(argv) {
295
+ const { help, ...args } = commandLineArgs(this.args, { argv });
296
+ if (help) {
297
+ console.log(commandLineUsage([
298
+ {
299
+ header: "Options",
300
+ optionList: this.args,
301
+ },
302
+ ]));
303
+ return;
304
+ }
305
+ return this.callback(args);
306
+ }
307
+ }
308
+ async function commandset(commands) {
309
+ const { command, help = false, _unknown: argv = [], } = commandLineArgs([
310
+ {
311
+ name: "command",
312
+ type: String,
313
+ defaultOption: true,
314
+ },
315
+ {
316
+ name: "help",
317
+ alias: "h",
318
+ type: Boolean,
319
+ // @ts-ignore
320
+ description: "Display this usage guide.",
321
+ },
322
+ ], {
323
+ stopAtFirstUnknown: true,
324
+ });
325
+ if (!command || !(command in commands)) {
326
+ if (help) {
327
+ const commandsSummary = Object.keys(commands).map((key) => ({
328
+ name: key,
329
+ summary: commands[key].description,
330
+ }));
331
+ const usage = commandLineUsage([
332
+ {
333
+ header: "Synopsis",
334
+ content: "npx react-islands <command> <options>",
335
+ },
336
+ {
337
+ header: "Command List",
338
+ content: commandsSummary,
339
+ },
340
+ ]);
341
+ console.log(usage);
342
+ }
343
+ else {
344
+ console.error(`Command '${command}' not recognized by React Islands.`);
345
+ }
346
+ return;
347
+ }
348
+ return commands[command].run([...argv, help && "--help"].filter(Boolean));
349
+ }
350
+
351
+ var build = new Command({
352
+ description: "Build and statically render the islands.",
353
+ args: [
354
+ {
355
+ name: "config",
356
+ type: String,
357
+ alias: "c",
358
+ // @ts-ignore
359
+ description: "The config file to use.",
360
+ defaultValue: "islands.config.json",
361
+ },
362
+ ],
363
+ callback: async (args) => {
364
+ const { config } = args;
365
+ const configJson = JSON.parse(readFileSync(config, "utf8"));
366
+ const { islands, ...restConfig } = configJson;
367
+ if (restConfig.common !== false) {
368
+ const spinner = yoctoSpinner({
369
+ text: `Creating common dependencies file...`,
370
+ }).start();
371
+ const commonRollupConfig = createCommonConfig(restConfig);
372
+ const { output, ...input } = commonRollupConfig;
373
+ const success = await runRollup(input, output);
374
+ if (success) {
375
+ spinner.success(`Succeeded: common dependencies file`);
376
+ }
377
+ else {
378
+ spinner.warning(`Failed: common dependencies file`);
379
+ }
380
+ }
381
+ for (const [name, input] of Object.entries(islands)) {
382
+ const spinner = yoctoSpinner({
383
+ text: `Creating island ${name}...`,
384
+ }).start();
385
+ const rollupConfigs = createRollupConfigs({
386
+ input,
387
+ name,
388
+ ...restConfig,
389
+ });
390
+ let hadFailure = false;
391
+ for (const rollupConfig of rollupConfigs) {
392
+ const { output, ...input } = rollupConfig;
393
+ const success = await runRollup(input, output);
394
+ if (!success) {
395
+ hadFailure = true;
396
+ }
397
+ }
398
+ rollupConfigs.map(async (options) => { });
399
+ if (hadFailure) {
400
+ spinner.warning(`Failed island: ${name}`);
401
+ }
402
+ else {
403
+ spinner.success(`Succeeded island: ${name}`);
404
+ }
405
+ }
406
+ },
407
+ });
408
+
409
+ commandset({
410
+ build,
411
+ });
package/dist/index.d.ts CHANGED
@@ -1,9 +1,49 @@
1
- import { WebpackOptionsNormalized, Compiler } from 'webpack';
1
+ import { FC } from 'react';
2
+ import { JsxPreset } from 'rollup';
2
3
 
3
- declare class ReactIslandsWebpackPlugin {
4
- createSubCompiler(dir: string, entry: Record<string, any>, options: WebpackOptionsNormalized): Compiler;
5
- apply(compiler: Compiler): Promise<void>;
4
+ interface IslandRenderOptions {
5
+ shouldHydrate: boolean;
6
+ multiple: boolean;
7
+ keepChildren: boolean;
6
8
  }
7
- declare function createIsland(name: string, Component: React.FC): void;
9
+ interface IslandOpts extends Partial<IslandRenderOptions> {
10
+ }
11
+ declare class Island {
12
+ readonly component: React.FC;
13
+ readonly renderOptions: IslandRenderOptions;
14
+ constructor(component: React.FC, opts?: IslandOpts);
15
+ private getProps;
16
+ private getRoots;
17
+ render(name: string): void;
18
+ }
19
+
20
+ /**
21
+ * Create a higher-order component with certain fixed.
22
+ *
23
+ * Useful for quickly creating multiple variants of the same component to use as islands.
24
+ *
25
+ * @param component FC<T>
26
+ * @param setProps Partial<T>
27
+ * @returns FC<T>
28
+ */
29
+ declare function withProps<T>(component: FC<T>, setProps: Partial<T>): FC<T>;
30
+ /**
31
+ * Checks if the current script is running in a pre-render.
32
+ *
33
+ * @returns boolean
34
+ */
35
+ declare function isServer(): boolean;
36
+
37
+ type BuildOptions = {
38
+ name: string;
39
+ input: string;
40
+ output: string;
41
+ minify?: boolean;
42
+ ssg?: boolean;
43
+ jsx?: JsxPreset;
44
+ typescript?: boolean;
45
+ common?: string[] | Record<string, string>;
46
+ };
8
47
 
9
- export { ReactIslandsWebpackPlugin, createIsland };
48
+ export { Island, isServer, withProps };
49
+ export type { BuildOptions };