Skip to content

Commit

Permalink
refactor: Minor adjustments to entry point / client script
Browse files Browse the repository at this point in the history
  • Loading branch information
rschristian committed Feb 2, 2023
1 parent 695bc10 commit a2fdd40
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 21 deletions.
5 changes: 5 additions & 0 deletions packages/cli/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ declare module 'shelljs' {
export = shell;
}

declare module 'preact-cli-entrypoint' {
const app: any;
export default app;
}

declare module '*.module.css' {
const classes: { [key: string]: string };
export default classes;
Expand Down
45 changes: 24 additions & 21 deletions packages/cli/src/lib/entry.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* global __webpack_public_path__ */

import * as Preact from 'preact';
const { h, render, hydrate } = Preact;
import { h, render, hydrate } from 'preact';

const interopDefault = m => (m && m.default ? m.default : m);

Expand All @@ -27,36 +26,40 @@ if (process.env.NODE_ENV === 'development') {
);
}

let app = interopDefault(require('preact-cli-entrypoint'));
const App = interopDefault(require('preact-cli-entrypoint'));

if (typeof app === 'function') {
let root =
document.getElementById('preact_root') || document.body.firstElementChild;

let init = () => {
let app = interopDefault(require('preact-cli-entrypoint'));
let prerenderData = {};
const inlineDataElement = document.querySelector(
'[type="__PREACT_CLI_DATA__"]'
if (typeof App === 'function') {
const init = () => {
const prerenderDataElement = document.querySelector(
'script[type="__PREACT_CLI_DATA__"]'
);
if (inlineDataElement) {
let prerenderData = {};

const root =
(prerenderDataElement && prerenderDataElement.parentElement) ||
document.body;

if (prerenderDataElement) {
prerenderData =
JSON.parse(decodeURI(inlineDataElement.innerHTML)).prerenderData ||
JSON.parse(decodeURI(prerenderDataElement.innerHTML)).prerenderData ||
prerenderData;
}

/* An object named CLI_DATA is passed as a prop,
* this keeps us future proof if in case we decide,
* to send other data like at some point in time.
*/
const CLI_DATA = { prerenderData };
const currentURL = prerenderData.url ? normalizeURL(prerenderData.url) : '';
const canHydrate =
process.env.PRERENDER &&
process.env.NODE_ENV === 'production' &&
hydrate &&
currentURL === normalizeURL(location.pathname);
const doRender = canHydrate ? hydrate : render;
doRender(h(app, { CLI_DATA }), document.body, root);

if (
prerenderDataElement &&
currentURL === normalizeURL(location.pathname)
) {
hydrate(h(App, { CLI_DATA }), root);
} else {
render(h(App, { CLI_DATA }), root);
}
};

if (module.hot) module.hot.accept('preact-cli-entrypoint', init);
Expand Down

0 comments on commit a2fdd40

Please sign in to comment.