Skip to content

Commit

Permalink
(wmr) - support typescript configs (#437)
Browse files Browse the repository at this point in the history
* support typescript configs

* sep branch

* attempt making test

* make imports work
  • Loading branch information
JoviDeCroock authored Mar 17, 2021
1 parent 4306e14 commit 2405b8c
Show file tree
Hide file tree
Showing 14 changed files with 105 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/moody-cougars-watch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'wmr': patch
---

Support Typescript config files
1 change: 1 addition & 0 deletions packages/wmr/demo/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"type": "module",
"alias": {
"react": "preact/compat"
}
Expand Down
3 changes: 3 additions & 0 deletions packages/wmr/demo/wmr.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function (config) {
return config;
}
6 changes: 3 additions & 3 deletions packages/wmr/src/lib/compile-single-module.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const ROLLUP_FAST_OUTPUT = {
// @TODO: this cache needs to be sharded by `input` in order to actually do anything when `preserveModules:true` is enabled
let cache;

export const compileSingleModule = withCache(async (input, { cwd, out }) => {
export const compileSingleModule = withCache(async (input, { cwd, out, hmr = true }) => {
input = input.replace(/\.css\.js$/, '.css');
// console.log('compiling ' + input);
const bundle = await rollup.rollup({
Expand Down Expand Up @@ -54,9 +54,9 @@ export const compileSingleModule = withCache(async (input, { cwd, out }) => {
}),
// localNpmPlugin(),
// wmrStylesPlugin({ cwd }),
wmrPlugin(),
hmr && wmrPlugin(),
htmPlugin()
]
].filter(Boolean)
});
cache = bundle.cache;
const result = await bundle.write({
Expand Down
27 changes: 19 additions & 8 deletions packages/wmr/src/lib/normalize-options.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { resolve, join } from 'path';
import { promises as fs } from 'fs';
import url from 'url';
import { readEnvFiles } from './environment.js';
import { compileSingleModule } from './compile-single-module.js';

/**
* @template {Options} T
Expand Down Expand Up @@ -61,10 +62,19 @@ export async function normalizeOptions(options, mode) {
const pkg = fs.readFile(pkgFile, 'utf-8').then(JSON.parse);
options.aliases = (await pkg.catch(() => ({}))).alias || {};

const hasTsConfig = await isFile(resolve(options.root, 'wmr.config.ts'));
const hasMjsConfig = await isFile(resolve(options.root, 'wmr.config.mjs'));
if (hasMjsConfig || (await isFile(resolve(options.root, 'wmr.config.js')))) {
let custom,
initialConfigFile = hasMjsConfig ? 'wmr.config.mjs' : 'wmr.config.js',

let custom;
if (hasTsConfig) {
const resolved = resolve(options.root, 'wmr.config.ts');
await compileSingleModule(resolved, { cwd: options.cwd, out: resolve('.'), hmr: false });
const output = resolve('.', 'wmr.config.js');
const fileUrl = url.pathToFileURL(output);
custom = await eval('(x => import(x))')(fileUrl);
fs.unlink(resolve('.', 'wmr.config.js'));
} else if (hasMjsConfig || (await isFile(resolve(options.root, 'wmr.config.js')))) {
let initialConfigFile = hasMjsConfig ? 'wmr.config.mjs' : 'wmr.config.js',
initialError;
try {
const resolved = resolve(options.root, initialConfigFile);
Expand All @@ -83,11 +93,12 @@ export async function normalizeOptions(options, mode) {
throw Error(`Failed to load ${initialConfigFile}\n${initialError}\n${e}`);
}
}
Object.defineProperty(options, '_config', { value: custom });
if (custom) {
if (custom.default) await custom.default(options);
if (custom[mode]) await custom[mode](options);
}
}

Object.defineProperty(options, '_config', { value: custom });
if (custom) {
if (custom.default) await custom.default(options);
if (custom[mode]) await custom[mode](options);
}

// @ts-ignore-next
Expand Down
3 changes: 3 additions & 0 deletions packages/wmr/test/fixtures/publicpath-typescript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "module"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const minimum = 10;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background: red;
}
11 changes: 11 additions & 0 deletions packages/wmr/test/fixtures/publicpath-typescript/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<title>Simple + publicPath</title>
<link rel="stylesheet" href="/index.css" />
</head>
<body>
<script src="/index.js" type="module"></script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
document.getElementById('root').textContent = 'success';

import('./math.js').then(m => {
m.add(1, 2);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.sum {
color: green;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import styles from './math.css';

export function add(x, y) {
console.log('math styles', styles);
return import('./constants.js').then(mod => {
return x + y + mod.minimum;
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function (config) {
config.publicPath = 'https://cdn.example.com/';
};
37 changes: 37 additions & 0 deletions packages/wmr/test/production.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,43 @@ describe('production', () => {
// HTML script: https://cdn.example.com/assets/index.0544f0a6.css
expect(html.includes(`src="https://cdn.example.com/${roots[2]}"`)).toBe(true);
});

it('should respect `config.publicPath` value (ts)', async () => {
await loadFixture('publicpath-typescript', env);
instance = await runWmr(env.tmp.path, 'build');
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 assets = await readdir('dist/assets');
const chunks = await readdir('dist/chunks');
const roots = await readdir('dist');

expect(assets).toEqual([expect.stringMatching(/^index\.\w+\.css$/), expect.stringMatching(/^math\.\w+\.css$/)]);

expect(chunks).toEqual([expect.stringMatching(/^constants\.\w+\.js$/), expect.stringMatching(/^math\.\w+\.js$/)]);

expect(roots).toEqual(['assets', 'chunks', expect.stringMatching(/^index\.\w+\.js$/), 'index.html']);

const html = await fs.readFile(path.join(env.tmp.path, 'dist', 'index.html'), 'utf8');
const math = await fs.readFile(path.join(env.tmp.path, 'dist', 'chunks', chunks[1]), 'utf8');
const main = await fs.readFile(path.join(env.tmp.path, 'dist', roots[2]), 'utf8');

// https://cdn.example.com/assets/math.d41e7373.css
expect(math.includes(`("https://cdn.example.com/assets/${assets[1]}")`)).toBe(true);
expect(math.includes(`import("./${chunks[0]}")`)).toBe(true);

// (preload) https://cdn.example.com/assets/math.d41e7373.css
expect(main.includes(`$w_s$("https://cdn.example.com/assets/${assets[1]}")`)).toBe(true);

// HTML stylesheet: https://cdn.example.com/assets/index.0544f0a6.css
expect(html.includes(`href="https://cdn.example.com/assets/${assets[0]}"`)).toBe(true);

// HTML script: https://cdn.example.com/assets/index.0544f0a6.css
expect(html.includes(`src="https://cdn.example.com/${roots[2]}"`)).toBe(true);
});
});

describe('prerender', () => {
Expand Down

0 comments on commit 2405b8c

Please sign in to comment.