Skip to content

Commit c2ca1c6

Browse files
authored
Merge pull request #17 from neilpa/esbuild-path-resolution
Use builtin `esbuild` path resolution
2 parents 57da45d + 4393216 commit c2ca1c6

1 file changed

Lines changed: 12 additions & 25 deletions

File tree

index.js

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,36 +13,20 @@ module.exports = (options = { plugins: [] }) => ({
1313
setup: function (build) {
1414
const { rootDir = options.rootDir || process.cwd() } = options;
1515
const tmpDirPath = tmp.dirSync().name;
16-
1716
build.onResolve(
1817
{ filter: /.\.(css)$/, namespace: "file" },
1918
async (args) => {
20-
let sourceFullPath;
21-
22-
// Manual attempt at resolving from node_modules and other typical directories
23-
if (args.path.startsWith('.') || path.isAbsolute(args.path)) {
24-
sourceFullPath = path.resolve(args.resolveDir, args.path);
25-
} else {
26-
const modulePaths = [
27-
// possible locations for node modules, maybe this is not strictly necessary
28-
path.resolve(args.resolveDir, 'node_modules', args.path),
29-
path.resolve(rootDir, 'node_modules', args.path),
30-
path.resolve(rootDir, '../node_modules', args.path)
31-
];
32-
33-
for (const modulePath of modulePaths) {
34-
if (fs.existsSync(modulePath)) {
35-
// if we find the path we need, use it as the sourceFullPath
36-
sourceFullPath = modulePath;
37-
break;
38-
}
39-
}
40-
41-
if (!sourceFullPath) {
42-
throw new Error(`Cannot resolve module: ${args.path}`);
43-
}
19+
// use esbuild path resolution for node_modules, typescript paths, etc.
20+
// https://esbuild.github.io/plugins/#resolve
21+
const resolution = await build.resolve(args.path, {
22+
resolveDir: args.resolveDir,
23+
kind: args.kind,
24+
});
25+
if (resolution.errors.length > 0) {
26+
return { errors: result.errors }
4427
}
4528

29+
const sourceFullPath = resolution.path;
4630
const sourceExt = path.extname(sourceFullPath);
4731
const sourceBaseName = path.basename(sourceFullPath, sourceExt);
4832
const sourceDir = path.dirname(sourceFullPath);
@@ -61,8 +45,11 @@ module.exports = (options = { plugins: [] }) => ({
6145
// Write the result file
6246
await writeFile(tmpFilePath, result.css);
6347

48+
// https://esbuild.github.io/plugins/#on-resolve-results
6449
return {
6550
path: tmpFilePath,
51+
// watch for changes to the original input for automatic rebuilds
52+
watchFiles: [ sourceFullPath ],
6653
};
6754
}
6855
);

0 commit comments

Comments
 (0)