UNPKG

@thelabnyc/typed-scss-modules

Version:

TypeScript type definition generator for SCSS CSS Modules

58 lines (57 loc) 2.18 kB
import fs from "node:fs"; import { pathToFileURL } from "node:url"; export class AliasImporter { opts; constructor(opts) { this.opts = opts; } findFileUrl = (url, ctx) => { if (url in this.opts.aliases) { const file = this.opts.aliases[url]; // Try to resolve using includePaths first if (this.opts.includePaths && this.opts.includePaths.length > 0) { for (const includePath of this.opts.includePaths) { const basePath = pathToFileURL(includePath + "/"); const resolvedUrl = new URL(file, basePath); const filePath = resolvedUrl.pathname; if (fs.existsSync(filePath) || fs.existsSync(filePath + ".scss")) { return resolvedUrl; } } } // Fallback to resolve relative to the containing file's directory const basePath = ctx.containingUrl ? new URL("./", ctx.containingUrl) : pathToFileURL(process.cwd() + "/"); const resolvedUrl = new URL(file, basePath); return resolvedUrl; } const prefixMatch = Object.keys(this.opts.aliasPrefixes).find((prefix) => url.startsWith(prefix)); if (prefixMatch) { const basePath = ctx.containingUrl || pathToFileURL("node_modules"); return new URL(this.opts.aliasPrefixes[prefixMatch] + url.substr(prefixMatch.length), basePath); } return null; }; } /** * Construct custom SASS importers based on options. * * - Given aliases and alias prefix options, add a custom alias importer. * - Given custom SASS importer(s), append to the list of importers. */ export const customImporters = (opts) => { let importers = [ new AliasImporter({ aliases: opts.aliases || {}, aliasPrefixes: opts.aliasPrefixes || {}, includePaths: opts.includePaths || [], }), ]; if (opts.importers) { importers = importers.concat(opts.importers); } return importers; };