Skip to content

Commit e439bd6

Browse files
author
Jeff Escalante
committed
tack raw source on to loader context
1 parent 48ccd61 commit e439bd6

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

README.md

+6
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@ const fooFile = require('testing.foo')
3535
console.log(fooFile) // wow it's the contents!
3636
```
3737

38+
As an added bonus, this loader makes the buffered raw source available on the `loaderContext` object so that plugins can manipulate it in any way necessary.
39+
40+
Let's break down how this could be done. Inside any plugin hook, you have a `compilation` object. You can get the `loaderContext` for any of the modules that webpack is processing through `compilation.modules` -- just find the one(s) you want by name. Now you have a large object which is an instance of the `DependenciesBlock` class, with a bunch of great information on it. You can find the raw buffered source under the `_src` property if the file was loaded with the source-loader.
41+
42+
Wondering what sets this loader apart from [raw-loader](https://github.com/webpack/raw-loader)? This is it. Both loaders expose the file's contents to be required by webpack, but this loader also exposes the raw source for plugin processing. It also has tests, and is actively maintained, as a bonus.
43+
3844
### License & Contributing
3945

4046
- Details on the license [can be found here](LICENSE.md)

lib/index.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
module.exports = function (source, map) {
1+
module.exports = function (source) {
22
this.cacheable && this.cacheable()
3-
return 'module.exports = ' + JSON.stringify(source)
3+
this._module._src = source
4+
return 'module.exports = ' + JSON.stringify(String(source))
45
}
6+
module.exports.raw = true

test/index.js

+20
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,23 @@ test.cb('basic text content works correctly', (t) => {
2424
t.end()
2525
})
2626
})
27+
28+
test.cb('raw source is added to loader context', (t) => {
29+
webpack({
30+
context: fixturesPath,
31+
entry: path.join(fixturesPath, 'basic'),
32+
output: { path: fixturesPath, filename: 'build.js' },
33+
resolveLoader: {
34+
alias: { source: path.join(__dirname, '../lib/index.js') }
35+
},
36+
module: { loaders: [{ test: /\.txt$/, loader: 'source' }] }
37+
}, (err, res) => {
38+
if (err) { t.fail(err) }
39+
const mod = res.compilation.modules.find((m) => {
40+
return m.rawRequest === './hello.txt'
41+
})
42+
t.truthy(Buffer.isBuffer(mod._src))
43+
t.is(String(mod._src).trim(), 'hello there!')
44+
t.end()
45+
})
46+
})

0 commit comments

Comments
 (0)