Skip to content

Instantly share code, notes, and snippets.

@aackerman
Last active April 3, 2018 08:37
Show Gist options
  • Select an option

  • Save aackerman/9cbc7bcea1c827f5662a to your computer and use it in GitHub Desktop.

Select an option

Save aackerman/9cbc7bcea1c827f5662a to your computer and use it in GitHub Desktop.
Webpack dependency injection loader
var regex = /require\(([^\)]+)\)/g;
module.exports = function inject(src) {
this.cacheable();
return [
'module.exports = function inject(__injections__) {',
' var module = {exports: {}};',
' ' + src.replace(regex, '(__injections__[$1] || $&)'),
' return module.exports;',
'}'
].join("\n");
}

The output will look something like this.

var Square = (__injections__['dependency'] || __webpack_require__(4));

And the MockDependency will be used

import React from 'react';
import dependency from 'dependency';
export default React.createClass({
render() {
return <div/>
}
});
import SquareInjector from './inject!./square';
import MockDependency from './mock-dependency';
let Square = SquareInjector({
dependency: MockDependency
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment