Skip to content

Commit

Permalink
feat: support data as Function (#648)
Browse files Browse the repository at this point in the history
  • Loading branch information
evilebottnawi authored Dec 14, 2018
1 parent a8709c9 commit aa64e1b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,27 @@ If you want to prepend Sass code before the actual entry file, you can set the `
}
```

The `data` option supports `Function` notation:

```javascript
{
loader: "sass-loader",
options: {
data: (loaderContext) => {
// More information about avalaible options https://webpack.js.org/api/loaders/
const { resourcePath, rootContext } = loaderContext;
const relativePath = path.relative(rootContext,resourcePath);

if (relativePath === "styles/foo.scss") {
return "$value: 100px;"
}

return "$value: 200px;"
}
}
}
```

**Please note:** Since you're injecting code, this will break the source mappings in your entry file. Often there's a simpler solution than this, like multiple Sass entry files.

<h2 align="center">Maintainers</h2>
Expand Down
8 changes: 7 additions & 1 deletion lib/normalizeOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ function normalizeOptions(loaderContext, content, webpackImporter) {
const options = cloneDeep(utils.getOptions(loaderContext)) || {};
const { resourcePath } = loaderContext;

options.data = options.data ? options.data + os.EOL + content : content;
let { data } = options;

if (typeof options.data === 'function') {
data = options.data(loaderContext);
}

options.data = data ? data + os.EOL + content : content;

// opt.outputStyle
if (!options.outputStyle && loaderContext.minimize) {
Expand Down
12 changes: 11 additions & 1 deletion test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Object.defineProperty(loaderContextMock, 'options', {
},
});

/* global should */

implementations.forEach((implementation) => {
const [implementationName] = implementation.info.split('\t');

Expand Down Expand Up @@ -185,10 +187,18 @@ implementations.forEach((implementation) => {
}));
});
describe('prepending data', () => {
it('should extend the data-option if present', () =>
it('should extend the data option if present and it is string', () =>
execTest('prepending-data', {
data: `$prepended-data: hotpink${ext === 'sass' ? '\n' : ';'}`,
}));
it('should extend the data option if present and it is function', () =>
execTest('prepending-data', {
data: (loaderContext) => {
should.exist(loaderContext);

return `$prepended-data: hotpink${ext === 'sass' ? '\n' : ';'}`;
},
}));
});
// See https://github.com/webpack-contrib/sass-loader/issues/21
describe('empty files', () => {
Expand Down

0 comments on commit aa64e1b

Please sign in to comment.