Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix infinite loop when prerendering json imports #480

Merged
merged 4 commits into from
Mar 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tidy-lies-beam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'wmr': patch
---

Fix unable to load json files during prerendering
1 change: 1 addition & 0 deletions examples/demo/public/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export default function Header() {
<a href="/class-fields">Class-Fields</a>
<a href="/files">Files</a>
<a href="/env">Env</a>
<a href="/json">JSON</a>
<a href="/error">Error</a>
</nav>
<label>
Expand Down
3 changes: 2 additions & 1 deletion examples/demo/public/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const CompatPage = lazy(() => import('./pages/compat.js'));
const ClassFields = lazy(() => import('./pages/class-fields.js'));
const Files = lazy(() => import('./pages/files/index.js'));
const Environment = lazy(async () => (await import('./pages/environment/index.js')).Environment);
const JSONView = lazy(async () => (await import('./pages/json.js')).JSONView);

export function App() {
return (
Expand All @@ -35,6 +36,7 @@ export function App() {
<ClassFields path="/class-fields" />
<Files path="/files" />
<Environment path="/env" />
<JSONView path="/json" />
<NotFound default />
</Router>
</ErrorBoundary>
Expand All @@ -54,4 +56,3 @@ export async function prerender(data) {

// @ts-ignore
if (module.hot) module.hot.accept(u => hydrate(<u.module.App />, document.body));

4 changes: 4 additions & 0 deletions examples/demo/public/pages/foo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"foo": 42,
"bar": "bar"
}
19 changes: 19 additions & 0 deletions examples/demo/public/pages/json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useEffect, useState } from 'preact/hooks';
import json from './foo.json';

export function JSONView() {
const [fetched, setFetched] = useState(null);

useEffect(() => {
fetch('./pages/foo.json')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a thought: this feels like a missed opportunity to demonstrate import jsonUrl from 'url:./foo.json'; + fetch(jsonUrl). Otherwise, to the reader the relative path ./pages/foo.json looks like "magic", in the base context of public/pages/json.js.

.then(r => r.json())
.then(r => setFetched(r));
}, []);

return (
<div>
<p>import: {JSON.stringify(json)}</p>
<p>fetch: {JSON.stringify(fetched)}</p>
</div>
);
}
2 changes: 1 addition & 1 deletion packages/wmr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@
"prettier": "^2.0.5",
"puppeteer": "^3.3.0",
"resolve.exports": "^1.0.2",
"rollup": "^2.41.0",
"rollup": "^2.43.1",
"rollup-plugin-preserve-shebang": "^1.0.1",
"sade": "^1.7.3",
"semver": "^7.3.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/wmr/src/bundler.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export async function bundleProd({
}),
npmPlugin({ external: false }),
urlPlugin({}),
jsonPlugin(),
jsonPlugin({ cwd }),
...plugins.slice(split),
bundlePlugin({ cwd }),
optimizeGraphPlugin({ publicPath }),
Expand Down
35 changes: 29 additions & 6 deletions packages/wmr/src/plugins/json-plugin.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import path from 'path';
import { promises as fs } from 'fs';

/**
* Convert JSON imports to ESM. Uses a prefix `\0json:./foo.json`.
* In dev mode, this creates URLs like `/@json/path/to/foo.json`.
Expand All @@ -6,26 +9,46 @@
* import foo from './foo.json';
* import foo from 'json:./foo.json';
*
* @param {object?} [options]
* @param {object} options
* @param {string} options.cwd
* @returns {import('rollup').Plugin}
*/
export default function jsonPlugin({} = {}) {
export default function jsonPlugin({ cwd }) {
const IMPORT_PREFIX = 'json:';
const INTERNAL_PREFIX = '\0json:';

return {
name: 'json-plugin',
async resolveId(id, importer) {
if (id[0] === '\0' || !id.endsWith('.json')) return;

// always process prefixed imports
if (id.startsWith(IMPORT_PREFIX)) {
// always process prefixed imports
id = id.slice(IMPORT_PREFIX.length);
} else if (!id.endsWith('.json')) {
// not a JSON file, no prefix
return;
}

const resolved = await this.resolve(id, importer, { skipSelf: true });
return resolved && INTERNAL_PREFIX + resolved.id;
},
// TODO: If we find a way to remove the need for adding
// an internal prefix we can get rid of the whole
// loading logic here and let rollup handle that part.
async load(id) {
if (!id.endsWith('.json')) return null;

if (id.startsWith(INTERNAL_PREFIX)) {
id = id.slice(INTERNAL_PREFIX.length);
}

// TODO: Add a global helper function to normalize paths
// and check that we're allowed to load a file.
const file = path.resolve(cwd, id);
if (!file.startsWith(cwd)) {
throw new Error(`JSON file must be placed inside ${cwd}`);
}

return await fs.readFile(file, 'utf-8');
},
transform(code, id) {
if (!id.startsWith(INTERNAL_PREFIX)) return;

Expand Down
2 changes: 1 addition & 1 deletion packages/wmr/src/wmr-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export default function wmrMiddleware({
externalUrlsPlugin(),
nodeBuiltinsPlugin({}),
urlPlugin({ inline: true, cwd }),
jsonPlugin(),
jsonPlugin({ cwd }),
bundlePlugin({ inline: true, cwd }),
aliasesPlugin({ aliases, cwd: root }),
sucrasePlugin({
Expand Down
4 changes: 4 additions & 0 deletions packages/wmr/test/fixtures/prod-prerender-json/foo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"foo": 42,
"bar": "bar"
}
10 changes: 10 additions & 0 deletions packages/wmr/test/fixtures/prod-prerender-json/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<title>default title</title>
</head>
<body>
<script src="./index.js" type="module"></script>
</body>
</html>
11 changes: 11 additions & 0 deletions packages/wmr/test/fixtures/prod-prerender-json/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import foo from './foo.json';

export function prerender() {
document.title = `Page: ${location.pathname}`;

const html = `<div>
<h1>page = ${location.pathname}</h1>
<p>JSON: ${JSON.stringify(foo)}</p>
</div>`;
return { html, links: ['/'] };
}
23 changes: 20 additions & 3 deletions packages/wmr/test/production.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,16 +293,21 @@ describe('production', () => {
});

describe('prerender', () => {
/**
* @param {TestEnv} env
* @param {string} f
* @returns {Promise<string[]>}
*/
const readdir = async (env, f) => (await fs.readdir(path.join(env.tmp.path, f))).filter(f => f[0] !== '.');

it('should support prerendered HTML, title & meta tags', async () => {
await loadFixture('prod-head', env);
instance = await runWmr(env.tmp.path, 'build', '--prerender');
const code = await instance.done;
console.info(instance.output.join('\n'));
expect(code).toBe(0);

const readdir = async f => (await fs.readdir(path.join(env.tmp.path, f))).filter(f => f[0] !== '.');

const pages = await readdir('dist');
const pages = await readdir(env, 'dist');

expect(pages).toContain('index.html');
expect(pages).toContain('other.html');
Expand All @@ -319,6 +324,18 @@ describe('production', () => {
expect(other).toMatch('<h1>page = /other.html</h1>');
expect(other).toMatch(`<meta property="og:title" content="Become an SEO Expert">`);
});

it('should support prerendering json', async () => {
await loadFixture('prod-prerender-json', env);
instance = await runWmr(env.tmp.path, 'build', '--prerender');
const code = await instance.done;
console.info(instance.output.join('\n'));
expect(code).toBe(0);

const indexHtml = path.join(env.tmp.path, 'dist', 'index.html');
const index = await fs.readFile(indexHtml, 'utf8');
expect(index).toMatch(/{"foo":42,"bar":"bar"}/);
});
});

describe('Code Splitting', () => {
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6920,6 +6920,13 @@ rollup@^2.0.0, rollup@^2.39.0, rollup@^2.41.0:
optionalDependencies:
fsevents "~2.3.1"

rollup@^2.43.1:
version "2.43.1"
resolved "https://registry.yarnpkg.com/rollup/-/rollup-2.43.1.tgz#9e5c9208c2011de227ac6c93101e11dc12e88e04"
integrity sha512-kvRE6VJbiv4d8m2nGeccc3qRpzOMghAhu2KeITjyZVCjneIFLPQ3zm2Wmqnl0LcUg3FvDaV0MfKnG4NCMbiSfw==
optionalDependencies:
fsevents "~2.3.1"

rsvp@^4.8.4, rsvp@^4.8.5:
version "4.8.5"
resolved "https://registry.yarnpkg.com/rsvp/-/rsvp-4.8.5.tgz#c8f155311d167f68f21e168df71ec5b083113734"
Expand Down