From e439bd633ffaa615387709021ca7367d02ab8b24 Mon Sep 17 00:00:00 2001 From: Jeff Escalante Date: Thu, 19 May 2016 10:20:12 -0400 Subject: [PATCH] tack raw source on to loader context --- README.md | 6 ++++++ lib/index.js | 6 ++++-- test/index.js | 20 ++++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8d6cbce..cf7c95e 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/lib/index.js b/lib/index.js index 6066aa3..6352879 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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 diff --git a/test/index.js b/test/index.js index 45f54db..fa1a640 100644 --- a/test/index.js +++ b/test/index.js @@ -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() + }) +})