Skip to content

Commit

Permalink
Fix relative less file resolved as npm package in production
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Aug 30, 2021
1 parent 19b3e7b commit cbc98be
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/wicked-flies-report.md
@@ -0,0 +1,5 @@
---
'wmr': patch
---

Fix nested relative `.less` file resolved as npm package in production
15 changes: 11 additions & 4 deletions packages/wmr/src/plugins/less-plugin.js
@@ -1,6 +1,7 @@
import path from 'path';
import { createCodeFrame } from 'simple-code-frame';
import { resolveAlias } from '../lib/aliasing.js';
import { isFile } from '../lib/fs-utils.js';

/** @type {import('less') | undefined} */
let less;
Expand All @@ -17,11 +18,17 @@ const lessFileLoader = (resolve, root) =>
currentDirectory = path.join(root, currentDirectory);
}

// Supply fake importer for relative resolution
const importer = path.join(currentDirectory, 'fake.less');
const resolved = await resolve(file, importer, { skipSelf: true });
let resolvedId;
const maybeRelative = path.join(currentDirectory, file);
if (await isFile(maybeRelative)) {
resolvedId = maybeRelative;
} else {
// Supply fake importer for relative resolution
const importer = path.join(currentDirectory, 'fake.less');
const resolved = await resolve(file, importer, { skipSelf: true });

let resolvedId = resolved ? resolved.id : file;
resolvedId = resolved ? resolved.id : file;
}

// Support bare imports: `@import "bar"`
if (!path.isAbsolute(resolvedId)) {
Expand Down
@@ -0,0 +1 @@
@color: red;
12 changes: 12 additions & 0 deletions packages/wmr/test/fixtures/css-less-nested-relative/index.html
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Less</title>
<link rel="stylesheet" href="style.less" />
</head>
<body>
<h1>Less</h1>
<script type="module" src="index.js"></script>
</body>
</html>
Empty file.
@@ -0,0 +1,5 @@
@import 'foo';

h1 {
color: @color;
}
19 changes: 19 additions & 0 deletions packages/wmr/test/less.test.js
Expand Up @@ -224,5 +224,24 @@ describe('Less', () => {

expect(hash === newHash).toBeFalsy();
});

it('should correctly resolve nested relative files', async () => {
await loadFixture('css-less-nested-relative', env);
instance = await runWmr(env.tmp.path, 'build');

await withLog(instance.output, async () => {
const code = await instance.done;
expect(code).toEqual(0);

const dir = await fs.readdir(path.join(env.tmp.path, 'dist', 'assets'));
expect(dir.some(x => x.endsWith('.css'))).toBeTruthy();
const { address, stop } = serveStatic(path.join(env.tmp.path, 'dist'));
cleanup.push(stop);
await env.page.goto(address, {
waitUntil: ['networkidle0', 'load']
});
expect(await env.page.$eval('h1', el => getComputedStyle(el).color)).toBe('rgb(255, 0, 0)');
});
});
});
});

0 comments on commit cbc98be

Please sign in to comment.