Skip to content

Commit

Permalink
fix: resolving resources from dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
Wroud committed Nov 13, 2024
1 parent 4bbd007 commit e1969f1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
6 changes: 6 additions & 0 deletions packages/@wroud/vite-plugin-asset-resolver/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
// copy from https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts

export const KNOWN_ASSET_TYPES = [
// resources
"css",
"scss",
"sass",
"less",

// images
"apng",
"bmp",
Expand Down
37 changes: 19 additions & 18 deletions packages/@wroud/vite-plugin-asset-resolver/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import path from "path";
import fs from "fs";
import { DEFAULT_DIST, DEFAULT_SRC, KNOWN_ASSET_TYPES } from "./constants.js";
import type { PluginOption } from "vite";

Expand Down Expand Up @@ -33,22 +32,21 @@ export function assetResolverPlugin(
return [
{
name: "asset-resolver-plugin",
async resolveId(source, importer) {
if (regex.test(source)) {
if (!source || !importer) {
throw new Error("Source or importer is undefined in resolveId");
enforce: "pre",
resolveId: {
order: "pre",
async handler(source, importer, options) {
if (!importer || !regex.test(source)) {
return;
}

// Attempt default resolution
const resolved = await this.resolve(source, importer, {
skipSelf: true,
});
const resolved = await this.resolve(source, importer, options);
if (resolved) {
return resolved;
}

const importerDir = path.dirname(importer);
const pathParts = importerDir.split(path.sep);
const pathParts = importer.split(path.sep);

let distIndex = -1;
for (let i = pathParts.length - 1; i >= 0; i--) {
Expand All @@ -62,23 +60,26 @@ export function assetResolverPlugin(
for (const srcAlias of src) {
pathParts[distIndex] = srcAlias;

let adjustedImporterDir = path.join(...pathParts);
let adjustedImporter = path.join(...pathParts);

if (importerDir.startsWith("/")) {
adjustedImporterDir = "/" + adjustedImporterDir;
if (importer.startsWith("/")) {
adjustedImporter = "/" + adjustedImporter;
}

const srcPath = path.resolve(adjustedImporterDir, source);
const resolvedId = await this.resolve(
source,
adjustedImporter,
options,
);

if (fs.existsSync(srcPath)) {
return srcPath;
if (resolvedId) {
return resolvedId;
}
}
}

throw new Error(`Failed to resolve ${source} from ${importer}`);
}
return null;
},
},
},
];
Expand Down

0 comments on commit e1969f1

Please sign in to comment.