Use local npm modules for utility sub-modules

This commit is contained in:
SleepWalker
2016-07-23 00:21:04 +03:00
parent fc84fb49c6
commit 003a224688
6 changed files with 8 additions and 6 deletions

36
webpack-utils/cssUrl.js Normal file
View File

@@ -0,0 +1,36 @@
// при использовании sass-loader теряется контекст в импортированных модулях
// из-за чего css-loader не может правильно обработать относительные url
//
// препроцессим урлы перед тем, как пропускать их через sass-loader
// урлы, начинающиеся с / будут оставлены как есть
const cssUrl = require('postcss-url');
const loaderUtils = require('loader-utils');
// /#.+$/ - strip #hash part of svg font url
const urlToRequest = (url) => loaderUtils.urlToRequest(url.replace(/\??#.+$/, ''), true);
const urlPostfix = (url) => {
var idx = url.indexOf('?#');
if (idx < 0) {
idx = url.indexOf('#');
}
return idx >= 0 ? url.slice(idx) : '';
};
module.exports = function(loader) {
return cssUrl({
url: (url, decl, from, dirname, to, options, result) =>
new Promise((resolve, reject) =>
loaderUtils.isUrlRequest(url) ? loader.loadModule(urlToRequest(url), (err, source) =>
err ? reject(err) : resolve(
loader.exec(`
var __webpack_public_path__ = '${loader.options.output.publicPath}';
${source}
`) + urlPostfix(url)
)
) : resolve(url)
)
});
};

View File

@@ -0,0 +1,21 @@
module.exports = function() {
this.cacheable && this.cacheable();
var moduleId = this.context
.replace(this.options.resolve.root, '')
.replace(/^\/|\/$/g, '')
.replace(/\//g, '.');
var content = this.inputValue[0];
content = JSON.stringify(Object.keys(content).reduce(function(translations, key) {
translations[key] = {
id: moduleId + '.' + key,
defaultMessage: content[key]
};
return translations;
}, {}));
return 'import { defineMessages } from \'react-intl\';'
+ 'export default defineMessages(' + content + ')';
};

View File

@@ -0,0 +1,34 @@
var loaderUtils = require("loader-utils");
module.exports = function createImporter(options) {
return function(url, fileContext, done) {
if (options.test.test(url)) {
var request = loaderUtils.urlToRequest(url);
loaderContext.loadModule(request, function(err, source) {
if (err) return done(new Error(err));
done({
contents: loaderContext.exec(source)
});
});
} else {
done(false);
}
};
};
var loaderContext;
var Plugin = module.exports.Plugin = function() {};
Plugin.prototype.apply = function(compiler) {
compiler.plugin('compilation', function(compilation) {
compilation.plugin('normal-module-loader', setLoaderContext);
});
};
function setLoaderContext(instance) {
// inject loaderContext instance for importer function
loaderContext = instance;
}

View File

@@ -0,0 +1,10 @@
{
"name": "webpack-utils",
"version": "1.0.0",
"description": "",
"keywords": [],
"author": "",
"dependencies": {
"loader-utils": "^0.2.12"
}
}