Skip to content

Instantly share code, notes, and snippets.

@samuelmaddock
Created April 19, 2018 23:38
Show Gist options
  • Save samuelmaddock/7411d79de3e9eec56d6e569eec5c59b0 to your computer and use it in GitHub Desktop.
Save samuelmaddock/7411d79de3e9eec56d6e569eec5c59b0 to your computer and use it in GitHub Desktop.
webpack code to string loader with child compiler
import loaderUtils from 'loader-utils';
import SingleEntryPlugin from 'webpack/lib/SingleEntryPlugin';
/** StringLoader */
export default function loader() {}
export function pitch(request) {
const options = loaderUtils.getOptions(this) || {};
if (!this.webpack) {
throw new Error('This loader is only usable with webpack');
}
const cb = this.async();
const filename = loaderUtils.interpolateName(this, options.name || '[hash].inline.js', {
context: options.context || this.rootContext || this.options.context,
regExp: options.regExp,
});
const worker = {};
worker.options = {
filename,
chunkFilename: `[id].${filename}`,
namedChunkFilename: null,
};
worker.compiler = this._compilation
.createChildCompiler('inline', worker.options);
worker.compiler.apply(new SingleEntryPlugin(this.context, `!!${request}`, 'main'));
const subCache = `subcache ${__dirname} ${request}`;
worker.compilation = (compilation) => {
if (compilation.cache) {
if (!compilation.cache[subCache]) {
compilation.cache[subCache] = {};
}
compilation.cache = compilation.cache[subCache];
}
};
if (worker.compiler.hooks) {
const plugin = { name: 'StringLoader' };
worker.compiler.hooks.compilation.tap(plugin, worker.compilation);
} else {
worker.compiler.plugin('compilation', worker.compilation);
}
worker.compiler.runAsChild((err, entries, compilation) => {
if (err) return cb(err);
if (entries[0]) {
worker.file = entries[0].files[0];
const source = compilation.assets[worker.file].source()
delete this._compilation.assets[worker.file];
// see raw-loader
const json = JSON.stringify(source)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
return cb(null, `module.exports = ${json}`);
}
return cb(null, null);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment