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: url publicPath and assetDir can be a function #222

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions src/loaders/postcss/url/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ export interface UrlOptions {
* Public Path for URLs in CSS files
* @default "./"
*/
publicPath?: string;
publicPath?: string | ((original: string, resolved: string, file: string) => string);
/**
* Directory path for outputted CSS assets,
* which is not included into resulting URL
* @default "."
*/
assetDir?: string;
assetDir?: string | ((original: string, resolved: string, file: string) => string);
/**
* Enable/disable name generation with hash for outputted CSS assets
* or provide your own placeholder with the following blocks:
Expand All @@ -57,9 +57,11 @@ export interface UrlOptions {
}

const plugin: PluginCreator<UrlOptions> = (options = {}) => {
const defaultpublicPath = "./";
const defaultAssetDir = ".";
const inline = options.inline ?? false;
const publicPath = options.publicPath ?? "./";
const assetDir = options.assetDir ?? ".";
const publicPath = options.publicPath ?? defaultpublicPath;
const assetDir = options.assetDir ?? defaultAssetDir;
const resolve = options.resolve ?? resolveDefault;
const alias = options.alias ?? {};
const placeholder =
Expand Down Expand Up @@ -180,11 +182,21 @@ const plugin: PluginCreator<UrlOptions> = (options = {}) => {

usedNames.set(to, from);

const resolvedPublicPath =
typeof publicPath === "string"
? publicPath + (/[/\\]$/.test(publicPath) ? "" : "/") + path.basename(to)
: `${defaultpublicPath}${path.basename(to)}`;

node.type = "string";
node.value = publicPath + (/[/\\]$/.test(publicPath) ? "" : "/") + path.basename(to);
node.value =
typeof publicPath === "function"
? publicPath(node.value, resolvedPublicPath, file)
: resolvedPublicPath;

if (urlQuery) node.value += urlQuery;
to = normalizePath(typeof assetDir === "string" ? assetDir : defaultAssetDir, to);
to = typeof assetDir === "function" ? assetDir(from, to, file) : to;

to = normalizePath(assetDir, to);
res.messages.push({ plugin: name, type: "asset", to, source });
}

Expand Down