From 0f946e3befa723e7fe1e89c54f04aa8a97196f03 Mon Sep 17 00:00:00 2001 From: Karl von Randow Date: Thu, 28 Mar 2019 09:15:39 +1300 Subject: [PATCH] publicPathRelativeToSource option --- README.md | 40 ++++++++++++++++++++++++++++++++++++++++ src/loader.js | 5 +++++ 2 files changed, 45 insertions(+) diff --git a/README.md b/README.md index beb5620a..bfca003b 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,46 @@ module.exports = { } ``` +#### URLs relative to the CSS file + +URLs in CSS files are resolved by the browser relative to the CSS file itself. The `publicPath` option (above) is used +to specify where the root of the context is, relative to the CSS file for URLs in the CSS to work. However, having just +one `publicPath` means that all of your CSS files need to be at the same depth (number of directories deep). + +Use the `publicPathRelativeToSource` option to dynamically change the `publicPath` used by the `mini-css-extract-plugin` to +be relative to your source CSS file. NB: in order for the output to be correct, your output CSS file must be at the same +relative depth as your source CSS file. + +```js +const MiniCssExtractPlugin = require("mini-css-extract-plugin"); +module.exports = { + plugins: [ + new MiniCssExtractPlugin({ + // Options similar to the same options in webpackOptions.output + // both options are optional + filename: "[name].css", + chunkFilename: "[id].css" + }) + ], + module: { + rules: [ + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + options: { + publicPathRelativeToSource: true, + } + }, + "css-loader" + ] + } + ] + } +} +``` + #### Advanced configuration example This plugin should be used only on `production` builds without `style-loader` in the loaders chain, especially if you want to have HMR in `development`. diff --git a/src/loader.js b/src/loader.js index 9801d590..de6518f7 100644 --- a/src/loader.js +++ b/src/loader.js @@ -6,6 +6,7 @@ import NodeTargetPlugin from 'webpack/lib/node/NodeTargetPlugin'; import LibraryTemplatePlugin from 'webpack/lib/LibraryTemplatePlugin'; import SingleEntryPlugin from 'webpack/lib/SingleEntryPlugin'; import LimitChunkCountPlugin from 'webpack/lib/optimize/LimitChunkCountPlugin'; +import path from 'path'; const MODULE_TYPE = 'css/mini-extract'; const pluginName = 'mini-css-extract-plugin'; @@ -40,6 +41,10 @@ export function pitch(request) { filename: childFilename, publicPath, }; + if (query.publicPathRelativeToSource) { + const relative = path.relative(path.dirname(this.resourcePath), this.rootContext) + outputOptions.publicPath = relative + '/' + } const childCompiler = this._compilation.createChildCompiler( `${pluginName} ${request}`, outputOptions