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

[nextjs] Fix path resolution #310

Merged
merged 1 commit into from
Nov 11, 2024
Merged
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
82 changes: 34 additions & 48 deletions packages/pigment-css-unplugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
transform,
createFileReporter,
} from '@wyw-in-js/transform';
import { asyncResolveFallback, slugify } from '@wyw-in-js/shared';
import { slugify } from '@wyw-in-js/shared';
import {
UnpluginFactoryOutput,
WebpackPluginInstance,
Expand All @@ -25,7 +25,6 @@ import {
type PluginCustomOptions,
} from '@pigment-css/react/utils';
import { styledEngineMockup } from '@pigment-css/react/internal';

import { handleUrlReplacement, type AsyncResolver } from './utils';

type NextMeta = {
Expand Down Expand Up @@ -158,19 +157,6 @@ export const plugin = createUnplugin<PigmentOptions, true>((options) => {
};
const projectPath = meta?.type === 'next' ? meta.projectPath : process.cwd();

let webpackResolver: AsyncResolver;

const asyncResolve: AsyncResolver = async (what, importer, stack) => {
const result = await asyncResolveOpt?.(what, importer, stack);
if (typeof result === 'string') {
return result;
}
if (webpackResolver) {
return webpackResolver(what, importer, stack);
}
return asyncResolveFallback(what, importer, stack);
};

const withRtl = (selector: string, cssText: string) => {
return basePreprocessor(selector, cssText, css);
};
Expand All @@ -184,41 +170,41 @@ export const plugin = createUnplugin<PigmentOptions, true>((options) => {
transformInclude(id) {
return isZeroRuntimeProcessableFile(id, finalTransformLibraries);
},
webpack(compiler) {
compiler.resolverFactory.hooks.resolver
.for('normal')
.tap(`${pluginName}Resolver`, (resolver) => {
webpackResolver = (what: string, importer: string, stack: string[]) => {
const context = path.isAbsolute(importer)
? path.dirname(importer)
: path.join(projectPath, path.dirname(importer));
return new Promise((resolve, reject) => {
resolver.resolve(
{},
context,
what,
{
stack: new Set(stack),
},
(err, result) => {
if (typeof result !== 'string') {
reject(new Error(`${process.env.PACKAGE_NAME}: Could not resolve ${what}`));
} else if (result) {
resolve(result);
} else {
reject(err);
}
},
);
});
};
});
},
async transform(code, url) {
const [filePath] = url.split('?');
// Converts path separator as per platform, even on Windows, path segments have `/` instead of the usual `\`,
// so this function replaces such path separators.
const id = path.normalize(filePath);
// @ts-ignore
const nativeContext = this.getNativeBuildContext();
if (nativeContext?.framework !== 'webpack') {
throw new Error('This plugin should only be used with Webpack/Next.js.');
}
const asyncResolve = async (
token: string,
importer: string,
stack: string[],
): Promise<string> => {
const njsResult = await asyncResolveOpt?.(token, importer, stack);
if (typeof njsResult === 'string') {
return njsResult;
}
const context = path.isAbsolute(importer)
? path.dirname(importer)
: path.join(projectPath, path.dirname(importer));
return new Promise((resolve, reject) => {
nativeContext.loaderContext!.resolve(context, token, (err, result) => {
if (err) {
reject(err);
} else if (result) {
nativeContext.loaderContext!.addDependency(result);
resolve(result);
} else {
reject(new Error(`${process.env.PACKAGE_NAME}: Cannot resolve ${token}`));
}
});
});
};
const transformServices = {
options: {
filename: id,
Expand Down Expand Up @@ -344,13 +330,13 @@ export const plugin = createUnplugin<PigmentOptions, true>((options) => {
};
}

const rootPath = process.cwd();

const cssFilename = path
.normalize(`${id.replace(/\.[jt]sx?$/, '')}-${slug}.pigment.css`)
.replace(/\\/g, path.posix.sep);

const cssRelativePath = path.relative(rootPath, cssFilename).replace(/\\/g, path.posix.sep);
const cssRelativePath = path
.relative(projectPath, cssFilename)
.replace(/\\/g, path.posix.sep);
// Starting with null character so that it calls the resolver method (resolveId in line:430)
// Otherwise, webpack tries to resolve the path directly
const cssId = `\0${cssRelativePath}`;
Expand Down
Loading