Skip to content

Commit

Permalink
fix: respect rollup's sourcemap
Browse files Browse the repository at this point in the history
  • Loading branch information
Anidetrix committed Mar 18, 2020
1 parent 94ace05 commit cc6ad34
Show file tree
Hide file tree
Showing 9 changed files with 42 additions and 63 deletions.
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export default (options: Options = {}): Plugin => {
};

const res = await loaders.process(
{ code, map: this.getCombinedSourcemap().toString() },
{ code, map: options.sourceMap ? this.getCombinedSourcemap().toString() : undefined },
loaderContext,
);

Expand Down Expand Up @@ -183,7 +183,8 @@ export default (options: Options = {}): Plugin => {
for (const res of entries) {
const relative = relativePath(dir, res.id);
const map = res.map && new MapModifier(res.map).relative(fileDir).toObject();
concat.add(relative, res.code, map);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
concat.add(relative, res.code, map as any);
}

let code = concat.content.toString();
Expand Down
6 changes: 3 additions & 3 deletions src/loaders/less.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import loadModule from "../utils/load-module";
const loader: Loader = {
name: "less",
test: /\.less$/i,
async process(payload) {
async process({ code, map }) {
const less = loadModule("less");
if (!less) this.error("You need to install `less` package in order to process Less files");

Expand All @@ -15,7 +15,7 @@ const loader: Loader = {
less.render(code, options, (err, css) => (err ? reject(err) : resolve(css))),
);

const res = await render(payload.code, {
const res = await render(code, {
...this.options,
filename: this.id,
sourceMap: this.sourceMap
Expand All @@ -26,7 +26,7 @@ const loader: Loader = {
const deps = res.imports;
for (const dep of deps) this.dependencies.add(dep);

return { code: res.css, map: res.map };
return { code: res.css, map: res.map || map };
},
};

Expand Down
21 changes: 12 additions & 9 deletions src/loaders/postcss/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import postcss from "postcss";
import findPostCSSConfig from "postcss-load-config";
import cssnano from "cssnano";

import { Loader, PostCSSLoaderOptions, Payload } from "../../types";
import { Loader, PostCSSLoaderOptions } from "../../types";
import { humanlizePath, normalizePath } from "../../utils/path-utils";
import { MapModifier } from "../../utils/sourcemap-utils";
import resolveAsync from "../../utils/resolve-async";
Expand Down Expand Up @@ -57,7 +57,7 @@ const loader: Loader<PostCSSLoaderOptions> = {
name: "postcss",
alwaysProcess: true,
// `test` option is dynamically set in `Loaders` class
async process(payload) {
async process({ code, map, extracted }) {
const { options } = this;

const config = await loadConfig(this.id, options.config);
Expand Down Expand Up @@ -89,8 +89,8 @@ const loader: Loader<PostCSSLoaderOptions> = {

delete postcssOpts.plugins;

if (typeof postcssOpts.map === "object" && payload.map)
postcssOpts.map.prev = new MapModifier(payload.map)
if (typeof postcssOpts.map === "object" && map)
postcssOpts.map.prev = new MapModifier(map)
.relative(path.dirname(postcssOpts.from))
.toObject();

Expand Down Expand Up @@ -129,16 +129,20 @@ const loader: Loader<PostCSSLoaderOptions> = {
// You did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js
if (plugins.length === 0) plugins.push(postcssNoop);

const res = await postcss(plugins).process(payload.code, postcssOpts);
const res = await postcss(plugins).process(code, postcssOpts);

const deps = res.messages.filter(msg => msg.type === "dependency");
for (const dep of deps) this.dependencies.add(dep.file);

for (const warning of res.warnings())
this.warn(warning.text, { column: warning.column, line: warning.line });

const map =
res.map && new MapModifier(res.map.toJSON()).resolve(path.dirname(postcssOpts.to)).toString();
if (res.map) {
map =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new MapModifier(res.map.toJSON() as any).resolve(path.dirname(postcssOpts.to)).toString() ||
map;
}

if (!shouldExtract && this.sourceMap && map)
res.css += new MapModifier(map)
Expand All @@ -156,7 +160,7 @@ const loader: Loader<PostCSSLoaderOptions> = {
for (const name in json) {
const newName = getClassName(name);

// Skip logging when namedExports is a function since user can log that manually
// Skip logging when namedExports is a function since user can do that manually
if (name !== newName && typeof options.namedExports !== "function")
this.warn(`Exported "${name}" as "${newName}" in ${humanlizePath(this.id)}`);

Expand All @@ -167,7 +171,6 @@ const loader: Loader<PostCSSLoaderOptions> = {
}

const cssVarName = safeId("css");
let extracted: Payload["extracted"];
if (shouldExtract) {
output += `\nexport default ${JSON.stringify(modulesExports[this.id])};`;
extracted = { id: this.id, code: res.css, map };
Expand Down
6 changes: 3 additions & 3 deletions src/loaders/sass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ function loadSassOrThrow(): [Sass, AllowedSassID] {
const loader: Loader<SASSLoaderOptions> = {
name: "sass",
test: /\.(sass|scss)$/i,
process(payload) {
process({ code, map }) {
const [sass, sassType] = loadSassOrThrow();

const render = (options: SASSOptions): Promise<SASSResult> =>
Expand All @@ -97,7 +97,7 @@ const loader: Loader<SASSLoaderOptions> = {
const res = await render({
...this.options,
file: this.id,
data: (this.options.data || "") + payload.code,
data: (this.options.data || "") + code,
indentedSyntax: /\.sass$/i.test(this.id),
sourceMap: Boolean(this.sourceMap) && this.id,
omitSourceMapUrl: true,
Expand All @@ -109,7 +109,7 @@ const loader: Loader<SASSLoaderOptions> = {
const deps = res.stats.includedFiles;
for (const dep of deps) this.dependencies.add(dep);

return { code: res.css.toString(), map: res.map && res.map.toString() };
return { code: res.css.toString(), map: (res.map && res.map.toString()) || map };
},
);
},
Expand Down
4 changes: 2 additions & 2 deletions src/loaders/sourcemap.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Loader } from "../types";
import { getMap, stripMap } from "../utils/sourcemap-utils";
import { stripMap, getMap } from "../utils/sourcemap-utils";

const loader: Loader = {
name: "sourcemap",
alwaysProcess: true,
async process({ code, map }) {
if (!map) map = await getMap(code, this.id);
if (this.sourceMap) map = (await getMap(code, this.id)) || map;
return { code: stripMap(code), map };
},
};
Expand Down
23 changes: 12 additions & 11 deletions src/loaders/stylus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import { MapModifier } from "../utils/sourcemap-utils";
const loader: Loader = {
name: "stylus",
test: /\.(styl|stylus)$/i,
async process(payload) {
async process({ code, map }) {
const stylus = loadModule("stylus");
if (!stylus)
this.error("You need to install `stylus` package in order to process Stylus files");

const style = stylus(payload.code, { ...this.options })
const style = stylus(code, { ...this.options })
.set("filename", this.id)
.set(
"sourcemap",
Expand All @@ -24,19 +24,20 @@ const loader: Loader = {
style.render((err, css) => (err ? reject(err) : resolve(css)));
});

const code = await render();
code = await render();

const deps = style.deps();
for (const dep of deps) this.dependencies.add(dep);

const map =
style.sourcemap &&
new MapModifier(style.sourcemap)
.modify(map => {
// We have to manually modify the sourcesContent field since stylus compiler doesn't support it yet
if (!map.sourcesContent) map.sourcesContent = [code];
})
.toString();
if (style.sourcemap) {
map =
new MapModifier(style.sourcemap)
.modify(map => {
// We have to manually modify the sourcesContent field since stylus compiler doesn't support it yet
if (!map.sourcesContent) map.sourcesContent = [code];
})
.toString() || map;
}

return { code, map };
},
Expand Down
18 changes: 0 additions & 18 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,6 @@ import { LocalByDefaultOptions } from "postcss-modules-local-by-default";
import { ExtractImportsOptions } from "postcss-modules-extract-imports";
import { ScopeOptions } from "postcss-modules-scope";

/** Sourcemap */
export interface SourceMap {
/** Version */
version: string;
/** Sources */
sources: string[];
/** Names */
names: string[];
/** Sources content */
sourcesContent?: string[];
/** Mappings */
mappings: string;
/** File */
file?: string;
/** Source root */
sourceRoot?: string;
}

/** Object, which properties are unknown */
export type ObjectWithUnknownProps = { [prop: string]: unknown };

Expand Down
12 changes: 2 additions & 10 deletions src/typings/stylus.d.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
declare module "stylus" {
interface SourceMap {
version: string;
sources: string[];
names: string[];
sourcesContent?: string[];
mappings: string;
file?: string;
sourceRoot?: string;
}
import { ExistingRawSourceMap } from "rollup";

export interface Stylus {
(str: string): Renderer;
Expand All @@ -19,7 +11,7 @@ declare module "stylus" {
export class Renderer {
constructor(str: string);
constructor(str: string, options: RenderOptions);
sourcemap?: SourceMap;
sourcemap?: ExistingRawSourceMap;
render(callback: RenderCallback): void;
render(): string;
deps(): string[];
Expand Down
10 changes: 5 additions & 5 deletions src/utils/sourcemap-utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import path from "path";
import fs from "fs-extra";
import { ExistingRawSourceMap } from "rollup";
import {
relativePath,
isAbsolutePath,
normalizePath,
isRelativePath,
resolvePath,
} from "./path-utils";
import { SourceMap } from "../types";

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 @@ -70,10 +70,10 @@ export function stripMap(code: string): string {
* Class for working with sourcemaps, supports chaining
*/
export class MapModifier {
private map: SourceMap;
private map: ExistingRawSourceMap;

/** @param map sourcemap */
constructor(map: string | SourceMap) {
constructor(map: string | ExistingRawSourceMap) {
if (!map) throw new TypeError("Sourcemap must be an object or a string");
this.map = typeof map === "string" ? JSON.parse(map) : map;
}
Expand All @@ -83,7 +83,7 @@ export class MapModifier {
* @param f function used to modify the sourcemap
* @returns itself for chaining
*/
modify(f: (m: SourceMap) => void): this {
modify(f: (m: ExistingRawSourceMap) => void): this {
f(this.map);
return this;
}
Expand Down Expand Up @@ -121,7 +121,7 @@ export class MapModifier {
* Returns sourcemap
* @returns sourcemap object
*/
toObject(): SourceMap {
toObject(): ExistingRawSourceMap {
return this.map;
}

Expand Down

0 comments on commit cc6ad34

Please sign in to comment.