|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +if (global._cssModulesPolyfill) { |
| 4 | + throw new Error('only one instance of css-modules/polyfill is allowed'); |
| 5 | +} |
| 6 | + |
| 7 | +global._cssModulesPolyfill = true; |
| 8 | + |
| 9 | +var assign = require('object-assign'); |
| 10 | +var options = {}; |
| 11 | + |
| 12 | +/** |
| 13 | + * Posibility to pass custom options to the module |
| 14 | + * @param {object} opts |
| 15 | + */ |
| 16 | +module.exports = function (opts) { |
| 17 | + assign(options, opts); |
| 18 | +}; |
| 19 | + |
| 20 | +var Core = require('css-modules-loader-core'); |
| 21 | +var pluginsCache; |
| 22 | + |
| 23 | +/** |
| 24 | + * Caching plugins for the future calls |
| 25 | + * @return {array} |
| 26 | + */ |
| 27 | +function loadPlugins() { |
| 28 | + // retrieving from cache if they are already loaded |
| 29 | + if (pluginsCache) { |
| 30 | + return pluginsCache; |
| 31 | + } |
| 32 | + |
| 33 | + // PostCSS plugins passed to FileSystemLoader |
| 34 | + var plugins = options.use || options.u; |
| 35 | + if (!plugins) { |
| 36 | + plugins = Core.defaultPlugins; |
| 37 | + } else { |
| 38 | + if (typeof plugins === 'string') { |
| 39 | + plugins = [ plugins ]; |
| 40 | + } |
| 41 | + |
| 42 | + plugins = plugins.map(function requirePlugin (name) { |
| 43 | + // assume functions are already required plugins |
| 44 | + if (typeof name === 'function') { |
| 45 | + return name; |
| 46 | + } |
| 47 | + |
| 48 | + var plugin = require(require.resolve(name)); |
| 49 | + |
| 50 | + // custom scoped name generation |
| 51 | + if (name === 'postcss-modules-scope') { |
| 52 | + options[name] = options[name] || {}; |
| 53 | + options[name].generateScopedName = createScopedNameFunc(plugin); |
| 54 | + } |
| 55 | + |
| 56 | + if (name in options) { |
| 57 | + plugin = plugin(options[name]); |
| 58 | + } else { |
| 59 | + plugin = plugin.postcss || plugin(); |
| 60 | + } |
| 61 | + |
| 62 | + return plugin; |
| 63 | + }); |
| 64 | + } |
| 65 | + |
| 66 | + return pluginsCache = plugins; |
| 67 | +} |
| 68 | + |
| 69 | +var FileSystemLoader = require('css-modules-loader-core/lib/file-system-loader'); |
| 70 | +var path = require('path'); |
| 71 | + |
| 72 | +require.extensions['.css'] = function (m, filename) { |
| 73 | + var plugins = loadPlugins(); |
| 74 | + var loader = new FileSystemLoader(path.dirname(filename), plugins); |
| 75 | + var tokens = loader.fetchSync(path.basename(filename), '/'); |
| 76 | + |
| 77 | + return m._compile('module.exports = ' + JSON.stringify(tokens), filename); |
| 78 | +}; |
0 commit comments