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

feat: add "fileResolve" option for deep import resolving #142

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ declare interface Options {
Loader?: typeof Loader;

resolve?: (file: string) => string | Promise<string>;

fileResolve?: (
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 for updating the typings

file: string,
importer: string
) => string | null | Promise<string | null>;
}

declare interface PostcssModulesPlugin {
Expand Down
85 changes: 52 additions & 33 deletions src/css-loader-core/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const traceKeySorter = (a, b) => {
};

export default class FileSystemLoader {
constructor(root, plugins) {
constructor(root, plugins, fileResolve) {
if (root === "/" && process.platform === "win32") {
const cwdDrive = process.cwd().slice(0, 3);
if (!/^[A-Z]:\\$/.test(cwdDrive)) {
Expand All @@ -55,6 +55,7 @@ export default class FileSystemLoader {
}

this.root = root;
this.fileResolve = fileResolve;
this.sources = {};
this.traces = {};
this.importNr = 0;
Expand All @@ -65,43 +66,61 @@ export default class FileSystemLoader {
fetch(_newPath, relativeTo, _trace) {
let newPath = _newPath.replace(/^["']|["']$/g, ""),
trace = _trace || String.fromCharCode(this.importNr++);
const useFileResolve = typeof this.fileResolve === "function";
return new Promise((resolve, reject) => {
let relativeDir = path.dirname(relativeTo),
rootRelativePath = path.resolve(relativeDir, newPath),
fileRelativePath = path.resolve(
path.resolve(this.root, relativeDir),
newPath
);
(useFileResolve
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's rewrite this using async/await. I'm thinking of rewriting all the promises into async/await in the future

? this.fileResolve(newPath, relativeTo)
: Promise.resolve()
).then((fileResolvedPath) => {
if (fileResolvedPath && !path.isAbsolute(fileResolvedPath)) {
reject(
'The returned path from the "fileResolve" option must be absolute.'
);
}
let relativeDir = path.dirname(relativeTo),
madyankin marked this conversation as resolved.
Show resolved Hide resolved
rootRelativePath =
fileResolvedPath || path.resolve(relativeDir, newPath),
fileRelativePath =
fileResolvedPath ||
path.resolve(
path.resolve(this.root, relativeDir),
newPath
);

// if the path is not relative or absolute, try to resolve it in node_modules
if (newPath[0] !== "." && !path.isAbsolute(newPath)) {
try {
fileRelativePath = require.resolve(newPath);
} catch (e) {
// noop
// if the path is not relative or absolute, try to resolve it in node_modules
if (
!useFileResolve &&
newPath[0] !== "." &&
!path.isAbsolute(newPath)
) {
try {
fileRelativePath = require.resolve(newPath);
} catch (e) {
// noop
}
}
}

const tokens = this.tokensByFile[fileRelativePath];
if (tokens) {
return resolve(tokens);
}
const tokens = this.tokensByFile[fileRelativePath];
if (tokens) {
return resolve(tokens);
}

fs.readFile(fileRelativePath, "utf-8", (err, source) => {
if (err) reject(err);
this.core
.load(
source,
rootRelativePath,
trace,
this.fetch.bind(this)
)
.then(({ injectableSource, exportTokens }) => {
this.sources[fileRelativePath] = injectableSource;
this.traces[trace] = fileRelativePath;
this.tokensByFile[fileRelativePath] = exportTokens;
resolve(exportTokens);
}, reject);
fs.readFile(fileRelativePath, "utf-8", (err, source) => {
if (err) reject(err);
this.core
.load(
source,
rootRelativePath,
trace,
this.fetch.bind(this)
)
.then(({ injectableSource, exportTokens }) => {
this.sources[fileRelativePath] = injectableSource;
this.traces[trace] = fileRelativePath;
this.tokensByFile[fileRelativePath] = exportTokens;
resolve(exportTokens);
}, reject);
});
});
});
}
Expand Down
13 changes: 11 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ function getScopedNameGenerator(opts) {
function getLoader(opts, plugins) {
const root = typeof opts.root === "undefined" ? "/" : opts.root;
return typeof opts.Loader === "function"
? new opts.Loader(root, plugins)
: new FileSystemLoader(root, plugins);
? new opts.Loader(root, plugins, opts.fileResolve)
: new FileSystemLoader(root, plugins, opts.fileResolve);
}

function isGlobalModule(globalModules, inputFile) {
Expand Down Expand Up @@ -85,6 +85,15 @@ module.exports = (opts = {}) => {
if (resultPluginIndex === -1) {
throw new Error("Plugin missing from options.");
}
// resolve and fileResolve can't be used together
Copy link
Owner

@madyankin madyankin Oct 29, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for thinking about backwards compatibility. Anyway, I'd prefer to introduce a breaking change and bump the major version. So, let's remove the original resolve version, replace it with yours, and update the readme. Feel free to use the resolve option name for this.

if (
typeof opts.resolve === "function" &&
typeof opts.fileResolve == "function"
) {
throw new Error(
'Please use either the "resolve" or the "fileResolve" option.'
);
}
const earlierPlugins = result.processor.plugins.slice(
0,
resultPluginIndex
Expand Down
25 changes: 25 additions & 0 deletions test/__snapshots__/test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,31 @@ Object {
}
`;

exports[`processes fileResolve option: processes fileResolve option 1`] = `
"._composes_a_another-mixin {
display: flex;
height: 100px;
width: 200px;
}._composes_a_hello {
foo: bar;
}._composes_mixins_title {
color: black;
font-size: 40px;
}._composes_mixins_title:hover {
color: red;
}._composes_mixins_figure {
text-align: center
}._composes_mixins_title:focus, ._composes_mixins_figure:focus {
outline: none;
border: 1px solid red;
}._deepDeepCompose_deepDeepCompose {
}._deepDeepCompose_dotSlashRelativePath {
}._deepCompose_deepCompose {
content: \\"deepCompose\\";
}
"
`;

exports[`processes globalModulePaths option: processes globalModulePaths option 1`] = `
".page {
padding: 20px;
Expand Down
4 changes: 4 additions & 0 deletions test/fixtures/in/deepCompose.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.deepCompose {
composes: deepDeepCompose from "test-fixture-in/deepDeepCompose.css";
content: "deepCompose";
}
7 changes: 7 additions & 0 deletions test/fixtures/in/deepDeepCompose.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.deepDeepCompose {
composes: title from "test-fixture-in/composes.mixins.css";
}

.dotSlashRelativePath {
composes: title from "./composes.mixins.css";
}
47 changes: 47 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -415,3 +415,50 @@ it("processes resolve option", async () => {
"_compose_resolve_figure-single-quote _composes_a_hello",
});
});

it("processes fileResolve option", async () => {
const sourceFile = path.join(fixturesPath, "in", "deepCompose.css");
const source = fs.readFileSync(sourceFile).toString();
let json;
const result = await postcss([
plugin({
generateScopedName,
fileResolve: async (file, importer) => {
return path.resolve(
path.dirname(importer),
file.replace(/^test-fixture-in/, path.dirname(sourceFile))
);
},
getJSON: (_, result) => {
json = result;
},
}),
]).process(source, { from: sourceFile });

expect(result.css).toMatchSnapshot("processes fileResolve option");
expect(json).toStrictEqual({
deepCompose:
"_deepCompose_deepCompose _deepDeepCompose_deepDeepCompose _composes_mixins_title",
});
});

it("processes fileResolve and resolve option", async () => {
const sourceFile = path.join(fixturesPath, "in", "deepCompose.css");
const source = fs.readFileSync(sourceFile).toString();
const result = await postcss([
plugin({
generateScopedName,
resolve: (file) => file,
fileResolve: async (file, importer) => {
return path.resolve(
path.dirname(importer),
file.replace(/^test-fixture-in/, path.dirname(sourceFile))
);
},
}),
])
.process(source, { from: sourceFile })
.catch((error) => error);

expect(result instanceof Error).toBe(true);
});