Skip to content

Commit

Permalink
perf: relace import-cwd with resolve
Browse files Browse the repository at this point in the history
  • Loading branch information
Anidetrix committed Mar 19, 2020
1 parent d546e55 commit dd4310e
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 72 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@
"cssnano": "^4.1.10",
"hash.js": "^1.1.7",
"icss-utils": "^4.1.1",
"import-cwd": "^3.0.0",
"p-queue": "^6.3.0",
"postcss": "^7.0.27",
"postcss-load-config": "^2.1.0",
Expand Down
2 changes: 1 addition & 1 deletion src/loaders/less.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const loader: Loader = {
name: "less",
test: /\.less$/i,
async process({ code, map }) {
const less = loadModule("less");
const less = await loadModule("less");
if (!less) this.error("You need to install `less` package in order to process Less files");

const render = (code: string, options: Less.Options): Promise<Less.RenderOutput> =>
Expand Down
10 changes: 5 additions & 5 deletions src/loaders/sass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ const defaultImporter: SASSImporter = (url, importer, done) => {
* Loads Sass module or throws an error
* @returns A tuple in format [`loaded sass module`, `id`],
*/
function loadSassOrThrow(): [Sass, AllowedSassID] {
async function loadSassOrThrow(): Promise<[Sass, AllowedSassID]> {
// Loading one of the supported modules
for (const id of possibleSassIDs) {
const module = loadModule(id);
const module = await loadModule(id);
if (module) return [module, id];
}

Expand All @@ -76,8 +76,8 @@ function loadSassOrThrow(): [Sass, AllowedSassID] {
const loader: Loader<SASSLoaderOptions> = {
name: "sass",
test: /\.(sass|scss)$/i,
process({ code, map }) {
const [sass, sassType] = loadSassOrThrow();
async process({ code, map }) {
const [sass, sassType] = await loadSassOrThrow();

const render = (options: SASSOptions): Promise<SASSResult> =>
new Promise((resolve, reject) => {
Expand All @@ -86,7 +86,7 @@ const loader: Loader<SASSLoaderOptions> = {

let fiber: FiberConstructor | undefined;
// Disable `fibers` for testing, it doesn't work
if (sassType == "sass" && !process.env.STYLES_TEST) fiber = loadModule("fibers");
if (sassType == "sass" && !process.env.STYLES_TEST) fiber = await loadModule("fibers");

return workQueue.add<Payload>(
async (): Promise<Payload> => {
Expand Down
2 changes: 1 addition & 1 deletion src/loaders/stylus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const loader: Loader = {
name: "stylus",
test: /\.(styl|stylus)$/i,
async process({ code, map }) {
const stylus = loadModule("stylus");
const stylus = await loadModule("stylus");
if (!stylus)
this.error("You need to install `stylus` package in order to process Stylus files");

Expand Down
25 changes: 21 additions & 4 deletions src/utils/load-module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import importCwd from "import-cwd";
import { Sass } from "sass";
import { Sass as NodeSass } from "node-sass";
import { FiberConstructor } from "fibers";
import { Stylus } from "stylus";

import resolveAsync from "./resolve-async";

/**
* Interface for mapping module's name to it's type
*/
Expand All @@ -13,16 +14,32 @@ interface ModuleImportMap {
fibers: FiberConstructor;
less: LessStatic;
stylus: Stylus;
[k: string]: unknown;
}

export default <K extends keyof ModuleImportMap>(moduleId: K): ModuleImportMap[K] | undefined => {
export default async <K extends keyof ModuleImportMap>(
moduleId: K,
basedir = process.cwd(),
): Promise<ModuleImportMap[K] | undefined> => {
if (typeof moduleId !== "string") return;

// Trying to load module normally (relative to plugin directory)
try {
return require(moduleId);
} catch (error) {
// Ignore error
}

// Then, trying to load it relative to CWD
return importCwd.silent(moduleId) as ModuleImportMap[K] | undefined;
// Then, trying to load it relative to provided dir or CWD
try {
return require(await resolveAsync(moduleId, { basedir }));
} catch (error) {
// Ignore error
}

try {
return require(await resolveAsync(`./${moduleId}`, { basedir }));
} catch (error) {
return;
}
};
8 changes: 0 additions & 8 deletions src/utils/path-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,3 @@ export function humanlizePath(file: string): string {
export function isAbsolutePath(path: string): boolean {
return /^(?:\/|(?:[A-Za-z]:)?[/\\|])/.test(path);
}

/**
* @param path Path
* @returns `true` if `path` is relative, otherwise `false`
*/
export function isRelativePath(path: string): boolean {
return /^\.?\.[/\\]/.test(path);
}
13 changes: 3 additions & 10 deletions src/utils/sourcemap-utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import path from "path";
import fs from "fs-extra";
import { ExistingRawSourceMap } from "rollup";
import {
relativePath,
isAbsolutePath,
normalizePath,
isRelativePath,
resolvePath,
} from "./path-utils";
import { relativePath, isAbsolutePath, resolvePath } from "./path-utils";

export const dataURIRe = /data:[^\n\r;]+?(?:;charset=[^\n\r;]+?)?;base64,([\d+/A-Za-z]+={0,2})/;
export const mapBlockRe = /\/\*[#*@]+?\s*?sourceMappingURL\s*?=\s*?(\S+)\s*?\*+?\//;
Expand Down Expand Up @@ -106,12 +100,11 @@ export class MapModifier {
* @param dir path to resolve sourcemap sources relative to
* @returns itself for chaining
*/
relative(dir: string = process.cwd()): this {
relative(dir = process.cwd()): this {
if (this.map.sources) {
this.map.sources = this.map.sources.map(source => {
if (isAbsolutePath(source)) return relativePath(dir, source);
else if (isRelativePath(source)) return relativePath(dir, path.join(dir, source));
else return normalizePath(source);
else return relativePath(dir, path.join(dir, source));
});
}
return this;
Expand Down
1 change: 1 addition & 0 deletions test/fixtures/utils/fixture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = "this is fixture";
73 changes: 45 additions & 28 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,57 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import path from "path";
import loadModule from "../src/utils/load-module";
import { getInlineMap, getExtractedMap, stripMap, MapModifier } from "../src/utils/sourcemap-utils";
import path from "path";

process.env.STYLES_TEST = "true";

test("wrong util path", () => {
const wrong = loadModule("totallyWRONGPATH/here" as any);
expect(wrong).toBeUndefined();
});
describe("load-module", () => {
test("wrong path", async () => {
const wrong = await loadModule("totallyWRONGPATH/here");
expect(wrong).toBeUndefined();
});

test("inline map", () => {
let code = ".foo {color: red;}";
const wrongMap = getInlineMap(code);
expect(wrongMap).toBeUndefined();
code +=
"/*# sourceMappingURL=data:application/json;base64,e1RISVM6SVNBU09VUkNFTUFQU0lNVUxBVElPTn0= */";
const correctMap = getInlineMap(code);
expect(correctMap).toBe("{THIS:ISASOURCEMAPSIMULATION}");
});
test("correct cwd path", async () => {
const correct = await loadModule("test/fixtures/utils/fixture");
expect(correct).toBe("this is fixture");
});

test("file map", async () => {
const code = ".foo {color: red;}/*# sourceMappingURL=fixture.css.map */";
const wrongMap = await getExtractedMap(code, path.resolve("this/is/nonexistant/path.css"));
expect(wrongMap).toBeUndefined();
const correctMap = await getExtractedMap(code, path.resolve("test/fixtures/utils/pointless.css"));
expect(correctMap).toBe("{THIS:ISASOURCEMAPSIMULATION}");
test("correct path with custom basepath", async () => {
const correct = await loadModule("fixture", path.join(__dirname, "fixtures", "utils"));
expect(correct).toBe("this is fixture");
});
});

test("strip map", () => {
const code = ".foo {color: red;}/*# sourceMappingURL=fixture.css.map */";
expect(stripMap(code)).toBe(".foo {color: red;}");
});
describe("sourcemap-utils", () => {
test("inline map", () => {
let code = ".foo {color: red;}";
const wrongMap = getInlineMap(code);
expect(wrongMap).toBeUndefined();
code +=
"/*# sourceMappingURL=data:application/json;base64,e1RISVM6SVNBU09VUkNFTUFQU0lNVUxBVElPTn0= */";
const correctMap = getInlineMap(code);
expect(correctMap).toBe("{THIS:ISASOURCEMAPSIMULATION}");
});

test("file map", async () => {
const code = ".foo {color: red;}/*# sourceMappingURL=fixture.css.map */";
const wrongMap = await getExtractedMap(code, path.resolve("this/is/nonexistant/path.css"));
expect(wrongMap).toBeUndefined();
const correctMap = await getExtractedMap(
code,
path.resolve("test/fixtures/utils/pointless.css"),
);
expect(correctMap).toBe("{THIS:ISASOURCEMAPSIMULATION}");
});

test("strip map", () => {
const code = ".foo {color: red;}/*# sourceMappingURL=fixture.css.map */";
expect(stripMap(code)).toBe(".foo {color: red;}");
});

test("map modifier", () => {
const map = JSON.stringify({ sources: ["../a/b/../foo/bar.css", "../b/a/../bar/foo.css"] });
const relativeSrc = JSON.stringify(new MapModifier(map).relative().toObject().sources);
expect(relativeSrc).toBe(JSON.stringify(["../a/foo/bar.css", "../b/bar/foo.css"]));
test("map modifier", () => {
const map = JSON.stringify({ sources: ["../a/b/../foo/bar.css", "../b/a/../bar/foo.css"] });
const relativeSrc = JSON.stringify(new MapModifier(map).relative().toObject().sources);
expect(relativeSrc).toBe(JSON.stringify(["../a/foo/bar.css", "../b/bar/foo.css"]));
});
});
14 changes: 0 additions & 14 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3740,13 +3740,6 @@ import-cwd@^2.0.0:
dependencies:
import-from "^2.1.0"

import-cwd@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/import-cwd/-/import-cwd-3.0.0.tgz#20845547718015126ea9b3676b7592fb8bd4cf92"
integrity sha512-4pnzH16plW+hgvRECbDWpQl3cqtvSofHWh44met7ESfZ8UZOWWddm8hEyDTqREJ9RbYHY8gi8DqmaelApoOGMg==
dependencies:
import-from "^3.0.0"

import-fresh@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-2.0.0.tgz#d81355c15612d386c61f9ddd3922d4304822a546"
Expand All @@ -3770,13 +3763,6 @@ import-from@^2.1.0:
dependencies:
resolve-from "^3.0.0"

import-from@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/import-from/-/import-from-3.0.0.tgz#055cfec38cd5a27d8057ca51376d7d3bf0891966"
integrity sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ==
dependencies:
resolve-from "^5.0.0"

import-local@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.0.2.tgz#a8cfd0431d1de4a2199703d003e3e62364fa6db6"
Expand Down

0 comments on commit dd4310e

Please sign in to comment.