Skip to content
This repository was archived by the owner on Jul 16, 2021. It is now read-only.

Commit 0f946e3

Browse files
committed
publicPathRelativeToSource option
1 parent 272910c commit 0f946e3

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,46 @@ module.exports = {
7474
}
7575
```
7676

77+
#### URLs relative to the CSS file
78+
79+
URLs in CSS files are resolved by the browser relative to the CSS file itself. The `publicPath` option (above) is used
80+
to specify where the root of the context is, relative to the CSS file for URLs in the CSS to work. However, having just
81+
one `publicPath` means that all of your CSS files need to be at the same depth (number of directories deep).
82+
83+
Use the `publicPathRelativeToSource` option to dynamically change the `publicPath` used by the `mini-css-extract-plugin` to
84+
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
85+
relative depth as your source CSS file.
86+
87+
```js
88+
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
89+
module.exports = {
90+
plugins: [
91+
new MiniCssExtractPlugin({
92+
// Options similar to the same options in webpackOptions.output
93+
// both options are optional
94+
filename: "[name].css",
95+
chunkFilename: "[id].css"
96+
})
97+
],
98+
module: {
99+
rules: [
100+
{
101+
test: /\.css$/,
102+
use: [
103+
{
104+
loader: MiniCssExtractPlugin.loader,
105+
options: {
106+
publicPathRelativeToSource: true,
107+
}
108+
},
109+
"css-loader"
110+
]
111+
}
112+
]
113+
}
114+
}
115+
```
116+
77117
#### Advanced configuration example
78118

79119
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`.

src/loader.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import NodeTargetPlugin from 'webpack/lib/node/NodeTargetPlugin';
66
import LibraryTemplatePlugin from 'webpack/lib/LibraryTemplatePlugin';
77
import SingleEntryPlugin from 'webpack/lib/SingleEntryPlugin';
88
import LimitChunkCountPlugin from 'webpack/lib/optimize/LimitChunkCountPlugin';
9+
import path from 'path';
910

1011
const MODULE_TYPE = 'css/mini-extract';
1112
const pluginName = 'mini-css-extract-plugin';
@@ -40,6 +41,10 @@ export function pitch(request) {
4041
filename: childFilename,
4142
publicPath,
4243
};
44+
if (query.publicPathRelativeToSource) {
45+
const relative = path.relative(path.dirname(this.resourcePath), this.rootContext)
46+
outputOptions.publicPath = relative + '/'
47+
}
4348
const childCompiler = this._compilation.createChildCompiler(
4449
`${pluginName} ${request}`,
4550
outputOptions

0 commit comments

Comments
 (0)