Skip to content
This repository has been archived by the owner on Mar 17, 2021. It is now read-only.

Allow publicPath handler to return a function instead of string #327

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,12 @@ module.exports = {
if (/images/.test(context)) {
return `image_output_path/${url}`;
}

if (/runtime/.test(context)) {
return function(url) {
return window.customPublicPath + url;
}
}

return `public_path/${url}`;
},
Expand Down
5 changes: 4 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ export default function loader(content) {
}${url}`;
}

publicPath = JSON.stringify(publicPath);
publicPath =
typeof publicPath === 'function'
? `(${publicPath})("${url}")`
: JSON.stringify(publicPath);
}

if (typeof options.emitFile === 'undefined' || options.emitFile) {
Expand Down
12 changes: 12 additions & 0 deletions test/__snapshots__/publicPath-option.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ Object {
}
`;

exports[`when applied with \`publicPath\` option matches snapshot for \`{Function}\` value returning \`{Function}\` 1`] = `
Object {
"assets": Array [
"9c87cbf3ba33126ffd25ae7f2f6bbafb.png",
],
"source": "module.exports = (function publicPath(url) {
// eslint-disable-next-line no-undef
return window.imageCdnBasePath + url;
})(\\"9c87cbf3ba33126ffd25ae7f2f6bbafb.png\\");",
}
`;

exports[`when applied with \`publicPath\` option matches snapshot for \`{String}\` value 1`] = `
Object {
"assets": Array [
Expand Down
22 changes: 22 additions & 0 deletions test/publicPath-option.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,26 @@ describe('when applied with `publicPath` option', () => {

expect({ assets, source }).toMatchSnapshot();
});

it('matches snapshot for `{Function}` value returning `{Function}`', async () => {
const config = {
loader: {
test: /(png|jpg|svg)/,
options: {
publicPath() {
return function publicPath(url) {
// eslint-disable-next-line no-undef
return window.imageCdnBasePath + url;
};
},
},
},
};

const stats = await webpack('fixture.js', config);
const [module] = stats.toJson().modules;
const { assets, source } = module;

expect({ assets, source }).toMatchSnapshot();
});
});