Skip to content
Merged
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 @@ -35,6 +35,12 @@ const fooFile = require('testing.foo')
console.log(fooFile) // wow it's the contents!
```

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.

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.

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.

### License & Contributing

- Details on the license [can be found here](LICENSE.md)
Expand Down
6 changes: 4 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
module.exports = function (source, map) {
module.exports = function (source) {
this.cacheable && this.cacheable()
return 'module.exports = ' + JSON.stringify(source)
this._module._src = source
return 'module.exports = ' + JSON.stringify(String(source))
}
module.exports.raw = true
20 changes: 20 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,23 @@ test.cb('basic text content works correctly', (t) => {
t.end()
})
})

test.cb('raw source is added to loader context', (t) => {
webpack({
context: fixturesPath,
entry: path.join(fixturesPath, 'basic'),
output: { path: fixturesPath, filename: 'build.js' },
resolveLoader: {
alias: { source: path.join(__dirname, '../lib/index.js') }
},
module: { loaders: [{ test: /\.txt$/, loader: 'source' }] }
}, (err, res) => {
if (err) { t.fail(err) }
const mod = res.compilation.modules.find((m) => {
return m.rawRequest === './hello.txt'
})
t.truthy(Buffer.isBuffer(mod._src))
t.is(String(mod._src).trim(), 'hello there!')
t.end()
})
})