Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 9x 6x 9x 9x 9x 9x 9x 5x 40x 8x 20x 4x 27x 12x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 11x 11x 11x 11x 4x 10x 7x 7x 7x 7x 10x 10x 10x 10x 10x | import { promisify } from "util";
import path from "path";
import { fileURLToPath, pathToFileURL } from "../utils/url";
import { computeContentHash } from "../crypto";
import * as sass from "sass";
import { createFilter } from "@rollup/pluginutils";
/**
* @warning Rollup is added as a "devDependency",
* so no actual symbols should be imported.
* Interfaces and non-concrete types are ok.
*/
import type { Plugin as RollupPlugin, TransformResult } from "rollup";
import type { RollupPluginSassOptions, RollupPluginSassState } from "./types";
import {
getImporterListLegacy,
getImporterListModern,
} from "./utils/getImporterList";
import {
processRenderResponse,
INSERT_STYLE_ID,
} from "./utils/processRenderResponse";
import insertStyle from "./insertStyle";
import { getSyntax } from "./utils/helpers";
import { createNodeModulesSymlinkResolver } from "./utils/nodeModulesSymlinkResolver";
import nodeFsAdapter from "../node-fs-adapter";
const MATCH_SASS_FILENAME_RE = /\.sass$/;
const defaultIncludes = ["**/*.sass", "**/*.scss", "**/*.css"];
const defaultExcludes = "";
const defaultApi = "modern";
// Simple console logger for sass compile messages
const consoleLogger: sass.Logger = {
debug(message: string) {
console.debug(`[Sass debug]: ${message}`);
},
warn(message: string, { deprecation, span, stack }: sass.LoggerWarnOptions) {
console.warn(
`[${deprecation ? "Sass deprecation" : "Sass warning"}]: ${message}`,
);
if (span && stack) {
console.log(` ${span.context}at ${stack}`);
}
},
};
// Typescript syntax for CommonJs "default exports" compatible export
// @reference https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
export default function plugin(
options = {} as RollupPluginSassOptions,
): RollupPlugin {
const pluginOptions: RollupPluginSassOptions = Object.assign(
{
runtime: sass,
output: false,
insert: false,
api: defaultApi,
},
options,
);
const {
include = defaultIncludes,
exclude = defaultExcludes,
runtime: sassRuntime,
shouldExtract = () => false,
getExtractNameAndUrl = (url) => ({ name: url, url }),
rootDir,
} = pluginOptions;
const filter = createFilter(include, exclude);
// Only built when `rootDir` is provided, so plugin instances that don't
// opt in (the default `getExtractNameAndUrl` included) see the exact same
// `filePath` as before this option existed.
const nodeModulesSymlinkResolver = rootDir
? createNodeModulesSymlinkResolver(rootDir)
: undefined;
const pluginState: RollupPluginSassState = {
styles: [],
styleMaps: {},
};
return {
name: "rollup-plugin-sass",
// Rollup calls buildStart at the start of every build, including each
// rebuild in `--watch`/dev mode, where this plugin instance (and its
// closures) is reused across rebuilds. Reset the memoized node_modules
// symlink scan here so it can't outlive a single build and go stale if
// node_modules changes between rebuilds (e.g. a mid-session `pnpm
// install`).
buildStart() {
nodeModulesSymlinkResolver?.reset();
},
/** @see https://rollupjs.org/plugin-development/#resolveid */
resolveId(source) {
if (source === INSERT_STYLE_ID) {
return INSERT_STYLE_ID;
}
},
/** @see https://rollupjs.org/plugin-development/#load */
load(id) {
if (id === INSERT_STYLE_ID) {
return `export default ${insertStyle.toString()}`;
}
},
async transform(code, filePath) {
if (!filter(filePath)) {
return;
}
// @ts-ignore
const fs = options.fs || globalThis.__rollupFs || nodeFsAdapter;
const paths = [path.dirname(filePath), process.cwd()];
const { styleMaps, styles } = pluginState;
// Setup resolved css output bundle tracking, for use later in `generateBundle` method.
// ----
Eif (!styleMaps[filePath]) {
const mapEntry = {
id: filePath,
content: "", // Populated after sass compilation
};
styleMaps[filePath] = mapEntry;
styles.push(mapEntry);
}
switch (pluginOptions.api) {
case "modern": {
const { options: incomingSassOptions } = pluginOptions;
const invokeSass = async (
url: URL,
source: string,
): Promise<sass.CompileResult> => {
const compileOptions: sass.StringOptions<"async"> = {
...incomingSassOptions,
syntax: getSyntax(path.extname(url.pathname)),
loadPaths: (incomingSassOptions?.loadPaths || []).concat(paths),
importers: getImporterListModern(
incomingSassOptions?.importers,
fs,
),
url,
/** force sourceMap because right now rollup outputOptions are not available */
sourceMap: true,
logger: consoleLogger,
};
const compileResult: sass.CompileResult =
await sassRuntime.compileStringAsync(source, compileOptions);
const { loadedUrls } = compileResult;
loadedUrls.forEach((filePath) => {
this.addWatchFile(fileURLToPath(filePath));
});
return compileResult;
};
/**
* Using {@link compileStringAsync} to keep support of prepend information on each file,
* basically `data` option
*/
const source = incomingSassOptions?.data
? `${incomingSassOptions.data}${code}`
: code;
const compileResult: sass.CompileResult = await invokeSass(
pathToFileURL(filePath) as URL,
source,
);
const codeResult = await processRenderResponse(
pluginOptions,
filePath,
pluginState,
compileResult.css.toString().trim(),
fs,
nodeModulesSymlinkResolver,
);
const { sourceMap } = compileResult;
return {
code: codeResult || "",
map: sourceMap ? sourceMap : undefined,
} as TransformResult;
}
case "legacy": {
const { options: incomingSassOptions } = pluginOptions;
const renderOptions: sass.LegacyOptions<"async"> = {
...incomingSassOptions,
file: filePath,
data:
incomingSassOptions?.data && `${incomingSassOptions.data}${code}`,
indentedSyntax: MATCH_SASS_FILENAME_RE.test(filePath),
includePaths: (incomingSassOptions?.includePaths || []).concat(
paths,
),
importer: getImporterListLegacy(incomingSassOptions?.importer, fs),
logger: consoleLogger,
};
const res: sass.LegacyResult = await promisify(
sassRuntime.render.bind(sassRuntime),
)(renderOptions);
const codeResult = await processRenderResponse(
pluginOptions,
filePath,
pluginState,
res.css.toString().trim(),
fs,
nodeModulesSymlinkResolver,
);
// @todo Do we need to filter this call so it only occurs when rollup is in 'watch' mode?
res.stats.includedFiles.forEach((filePath: string) => {
this.addWatchFile(filePath);
});
// @note do not `catch` here - let error propagate to rollup level.
return {
code: codeResult || "",
map: { mappings: res.map ? res.map.toString() : "" },
} as TransformResult;
}
}
},
async generateBundle(outputOptions, _, isWrite) {
const fs = options.fs || globalThis.__rollupFs || nodeFsAdapter;
const { styles } = pluginState;
const { output, insert } = pluginOptions;
if (!isWrite || (!insert && (!styles.length || output === false))) {
return;
}
const css = styles.map((style) => style.content).join("");
Iif (typeof output === "string") {
await fs.mkdir(path.dirname(output), { recursive: true });
await fs.writeFile(output, css);
return;
}
Iif (typeof output === "function") {
output(css, styles);
return;
}
Iif (!insert && outputOptions.file && output === true) {
let dest = outputOptions.file;
if (dest.endsWith(".js") || dest.endsWith(".ts")) {
dest = dest.slice(0, -3);
}
dest = `${dest}.css`;
await fs.mkdir(path.dirname(dest), { recursive: true });
await fs.writeFile(dest, css);
return;
}
for (const { id, content } of styles) {
Eif (id && content && shouldExtract(id, content)) {
const contentHash = await computeContentHash(content);
// pnpm (and other symlink-based package managers) resolve
// symlinks before passing the module id to plugins, so `id` can
// be a real path under packages/<pkg>/dist/ with no
// node_modules ancestor — rewrite it through its node_modules
// symlink first so getExtractNameAndUrl sees a path it can
// compute a clean node_modules-relative name from.
const resolved = await nodeModulesSymlinkResolver?.resolve(fs, id);
const { name } = await getExtractNameAndUrl(
resolved?.filePath ?? id,
contentHash,
fs,
);
this.emitFile({
type: "asset",
fileName: name,
source: content,
});
}
}
},
};
}
|