This commit is contained in:
2022-07-18 02:50:52 +00:00
parent befd344ab0
commit 06181b34d6
8569 changed files with 818704 additions and 352705 deletions
+105 -72
View File
@@ -31,41 +31,92 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
function loader(content, map, meta) {
const options = (0, _loaderUtils.getOptions)(this) || {};
(0, _schemaUtils.default)(_options.default, options, {
async function loader(content, map, meta) {
const rawOptions = (0, _loaderUtils.getOptions)(this);
(0, _schemaUtils.default)(_options.default, rawOptions, {
name: 'CSS Loader',
baseDataPath: 'options'
});
const callback = this.async();
const sourceMap = options.sourceMap || false;
const plugins = [];
const callback = this.async();
let options;
if ((0, _utils.shouldUseModulesPlugins)(options.modules, this.resourcePath)) {
try {
options = (0, _utils.normalizeOptions)(rawOptions, this);
} catch (error) {
callback(error);
return;
}
const replacements = [];
const exports = [];
if ((0, _utils.shouldUseModulesPlugins)(options)) {
plugins.push(...(0, _utils.getModulesPlugins)(options, this));
}
const exportType = options.onlyLocals ? 'locals' : 'full';
const preRequester = (0, _utils.getPreRequester)(this);
const importPluginImports = [];
const importPluginApi = [];
const urlHandler = url => (0, _loaderUtils.stringifyRequest)(this, preRequester(options.importLoaders) + url);
plugins.push((0, _plugins.icssParser)({
urlHandler
}));
if (options.import !== false && exportType === 'full') {
if ((0, _utils.shouldUseImportPlugin)(options)) {
const resolver = this.getResolve({
conditionNames: ['style'],
extensions: ['.css'],
mainFields: ['css', 'style', 'main', '...'],
mainFiles: ['index', '...'],
restrictions: [/\.css$/i]
});
plugins.push((0, _plugins.importParser)({
imports: importPluginImports,
api: importPluginApi,
context: this.context,
rootContext: this.rootContext,
filter: (0, _utils.getFilter)(options.import, this.resourcePath),
urlHandler
resolver,
urlHandler: url => (0, _loaderUtils.stringifyRequest)(this, (0, _utils.getPreRequester)(this)(options.importLoaders) + url)
}));
}
if (options.url !== false && exportType === 'full') {
const urlPluginImports = [];
if ((0, _utils.shouldUseURLPlugin)(options)) {
const urlResolver = this.getResolve({
conditionNames: ['asset'],
mainFields: ['asset'],
mainFiles: [],
extensions: []
});
plugins.push((0, _plugins.urlParser)({
filter: (0, _utils.getFilter)(options.url, this.resourcePath, value => (0, _loaderUtils.isUrlRequest)(value)),
imports: urlPluginImports,
replacements,
context: this.context,
rootContext: this.rootContext,
filter: (0, _utils.getFilter)(options.url, this.resourcePath),
resolver: urlResolver,
urlHandler: url => (0, _loaderUtils.stringifyRequest)(this, url)
}));
}
const icssPluginImports = [];
const icssPluginApi = [];
if ((0, _utils.shouldUseIcssPlugin)(options)) {
const icssResolver = this.getResolve({
conditionNames: ['style'],
extensions: [],
mainFields: ['css', 'style', 'main', '...'],
mainFiles: ['index', '...']
});
plugins.push((0, _plugins.icssParser)({
imports: icssPluginImports,
api: icssPluginApi,
replacements,
exports,
context: this.context,
rootContext: this.rootContext,
resolver: icssResolver,
urlHandler: url => (0, _loaderUtils.stringifyRequest)(this, (0, _utils.getPreRequester)(this)(options.importLoaders) + url)
}));
} // Reuse CSS AST (PostCSS AST e.g 'postcss-loader') to avoid reparsing
@@ -80,64 +131,46 @@ function loader(content, map, meta) {
}
}
(0, _postcss.default)(plugins).process(content, {
from: this.resourcePath,
to: this.resourcePath,
map: options.sourceMap ? {
// Some loaders (example `"postcss-loader": "1.x.x"`) always generates source map, we should remove it
prev: sourceMap && map ? (0, _utils.normalizeSourceMap)(map) : null,
inline: false,
annotation: false
} : false
}).then(result => {
for (const warning of result.warnings()) {
this.emitWarning(new _Warning.default(warning));
}
const {
resourcePath
} = this;
let result;
const imports = [];
const apiImports = [];
const urlReplacements = [];
const icssReplacements = [];
const exports = [];
for (const message of result.messages) {
// eslint-disable-next-line default-case
switch (message.type) {
case 'import':
imports.push(message.value);
break;
case 'api-import':
apiImports.push(message.value);
break;
case 'url-replacement':
urlReplacements.push(message.value);
break;
case 'icss-replacement':
icssReplacements.push(message.value);
break;
case 'export':
exports.push(message.value);
break;
}
}
const {
localsConvention
} = options;
const esModule = typeof options.esModule !== 'undefined' ? options.esModule : false;
const importCode = (0, _utils.getImportCode)(this, exportType, imports, esModule);
const moduleCode = (0, _utils.getModuleCode)(result, exportType, sourceMap, apiImports, urlReplacements, icssReplacements, esModule);
const exportCode = (0, _utils.getExportCode)(exports, exportType, localsConvention, icssReplacements, esModule);
return callback(null, `${importCode}${moduleCode}${exportCode}`);
}).catch(error => {
try {
result = await (0, _postcss.default)(plugins).process(content, {
from: resourcePath,
to: resourcePath,
map: options.sourceMap ? {
prev: map ? (0, _utils.normalizeSourceMap)(map, resourcePath) : null,
inline: false,
annotation: false
} : false
});
} catch (error) {
if (error.file) {
this.addDependency(error.file);
}
callback(error.name === 'CssSyntaxError' ? new _CssSyntaxError.default(error) : error);
});
return;
}
for (const warning of result.warnings()) {
this.emitWarning(new _Warning.default(warning));
}
const imports = [].concat(icssPluginImports.sort(_utils.sort)).concat(importPluginImports.sort(_utils.sort)).concat(urlPluginImports.sort(_utils.sort));
const api = [].concat(importPluginApi.sort(_utils.sort)).concat(icssPluginApi.sort(_utils.sort));
if (options.modules.exportOnlyLocals !== true) {
imports.unshift({
importName: '___CSS_LOADER_API_IMPORT___',
url: (0, _loaderUtils.stringifyRequest)(this, require.resolve('./runtime/api'))
});
}
const importCode = (0, _utils.getImportCode)(imports, options);
const moduleCode = (0, _utils.getModuleCode)(result, api, replacements, options, this);
const exportCode = (0, _utils.getExportCode)(exports, replacements, options);
callback(null, `${importCode}${moduleCode}${exportCode}`);
}
+52 -26
View File
@@ -36,7 +36,12 @@
"type": "object",
"additionalProperties": false,
"properties": {
"compileType": {
"description": "Controls the extent to which css-loader will process module code (https://github.com/webpack-contrib/css-loader#type)",
"enum": ["module", "icss"]
},
"auto": {
"description": "Allows auto enable CSS modules based on filename (https://github.com/webpack-contrib/css-loader#auto).",
"anyOf": [
{
"instanceof": "RegExp"
@@ -50,6 +55,7 @@
]
},
"mode": {
"description": "Setup `mode` option (https://github.com/webpack-contrib/css-loader#mode).",
"anyOf": [
{
"enum": ["local", "global", "pure"]
@@ -59,42 +65,67 @@
}
]
},
"exportGlobals": {
"type": "boolean"
},
"localIdentName": {
"type": "string"
"description": "Allows to configure the generated local ident name (https://github.com/webpack-contrib/css-loader#localidentname).",
"type": "string",
"minLength": 1
},
"localIdentContext": {
"description": "Allows to redefine basic loader context for local ident name (https://github.com/webpack-contrib/css-loader#localidentcontext).",
"type": "string",
"minLength": 1
},
"localIdentHashPrefix": {
"description": "Allows to add custom hash to generate more unique classes (https://github.com/webpack-contrib/css-loader#localidenthashprefix).",
"type": "string",
"minLength": 1
},
"localIdentRegExp": {
"description": "Allows to specify custom RegExp for local ident name (https://github.com/webpack-contrib/css-loader#localidentregexp).",
"anyOf": [
{
"type": "string"
"type": "string",
"minLength": 1
},
{
"instanceof": "RegExp"
}
]
},
"context": {
"type": "string"
},
"hashPrefix": {
"type": "string"
},
"getLocalIdent": {
"anyOf": [
{
"type": "boolean"
},
{
"instanceof": "Function"
}
"description": "Allows to specify a function to generate the classname (https://github.com/webpack-contrib/css-loader#getlocalident).",
"instanceof": "Function"
},
"namedExport": {
"description": "Enables/disables ES modules named export for locals (https://github.com/webpack-contrib/css-loader#namedexport).",
"type": "boolean"
},
"exportGlobals": {
"description": "Allows to export names from global class or id, so you can use that as local name (https://github.com/webpack-contrib/css-loader#exportglobals).",
"type": "boolean"
},
"exportLocalsConvention": {
"description": "Style of exported classnames (https://github.com/webpack-contrib/css-loader#localsconvention).",
"enum": [
"asIs",
"camelCase",
"camelCaseOnly",
"dashes",
"dashesOnly"
]
},
"exportOnlyLocals": {
"description": "Export only locals (https://github.com/webpack-contrib/css-loader#exportonlylocals).",
"type": "boolean"
}
}
}
]
},
"icss": {
"description": "Enables/Disables handling the CSS module interoperable import/export format ((https://github.com/webpack-contrib/css-loader#icss)",
"type": "boolean"
},
"sourceMap": {
"description": "Enables/Disables generation of source maps (https://github.com/webpack-contrib/css-loader#sourcemap).",
"type": "boolean"
@@ -105,19 +136,14 @@
{
"type": "boolean"
},
{
"type": "string"
},
{
"type": "integer"
}
]
},
"localsConvention": {
"description": "Style of exported classnames (https://github.com/webpack-contrib/css-loader#localsconvention).",
"enum": ["asIs", "camelCase", "camelCaseOnly", "dashes", "dashesOnly"]
},
"onlyLocals": {
"description": "Export only locals (https://github.com/webpack-contrib/css-loader#onlylocals).",
"type": "boolean"
},
"esModule": {
"description": "Use the ES modules syntax (https://github.com/webpack-contrib/css-loader#esmodule).",
"type": "boolean"
+80 -67
View File
@@ -9,70 +9,90 @@ var _postcss = _interopRequireDefault(require("postcss"));
var _icssUtils = require("icss-utils");
var _loaderUtils = require("loader-utils");
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function makeRequestableIcssImports(icssImports) {
return Object.keys(icssImports).reduce((accumulator, url) => {
const tokensMap = icssImports[url];
const tokens = Object.keys(tokensMap);
if (tokens.length === 0) {
return accumulator;
}
const normalizedUrl = (0, _loaderUtils.urlToRequest)(url);
if (!accumulator[normalizedUrl]) {
// eslint-disable-next-line no-param-reassign
accumulator[normalizedUrl] = tokensMap;
} else {
// eslint-disable-next-line no-param-reassign
accumulator[normalizedUrl] = { ...accumulator[normalizedUrl],
...tokensMap
};
}
return accumulator;
}, {});
}
var _default = _postcss.default.plugin('postcss-icss-parser', options => (css, result) => {
var _default = _postcss.default.plugin('postcss-icss-parser', options => async css => {
const importReplacements = Object.create(null);
const extractedICSS = (0, _icssUtils.extractICSS)(css);
const icssImports = makeRequestableIcssImports(extractedICSS.icssImports);
const {
icssImports,
icssExports
} = (0, _icssUtils.extractICSS)(css);
const imports = new Map();
const tasks = []; // eslint-disable-next-line guard-for-in
for (const [importIndex, url] of Object.keys(icssImports).entries()) {
const importName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}___`;
result.messages.push({
type: 'import',
value: {
importName,
url: options.urlHandler ? options.urlHandler(url) : url
}
}, {
type: 'api-import',
value: {
type: 'internal',
importName,
dedupe: true
}
});
const tokenMap = icssImports[url];
const tokens = Object.keys(tokenMap);
for (const url in icssImports) {
const tokens = icssImports[url];
for (const [replacementIndex, token] of tokens.entries()) {
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}_REPLACEMENT_${replacementIndex}___`;
const localName = tokenMap[token];
if (Object.keys(tokens).length === 0) {
// eslint-disable-next-line no-continue
continue;
}
let normalizedUrl = url;
let prefix = '';
const queryParts = normalizedUrl.split('!');
if (queryParts.length > 1) {
normalizedUrl = queryParts.pop();
prefix = queryParts.join('!');
}
const request = (0, _utils.requestify)((0, _utils.normalizeUrl)(normalizedUrl, true), options.rootContext);
const doResolve = async () => {
const {
resolver,
context
} = options;
const resolvedUrl = await (0, _utils.resolveRequests)(resolver, context, [...new Set([normalizedUrl, request])]);
return {
url: resolvedUrl,
prefix,
tokens
};
};
tasks.push(doResolve());
}
const results = await Promise.all(tasks);
for (let index = 0; index <= results.length - 1; index++) {
const {
url,
prefix,
tokens
} = results[index];
const newUrl = prefix ? `${prefix}!${url}` : url;
const importKey = newUrl;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_ICSS_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
options.imports.push({
importName,
url: options.urlHandler(newUrl),
icss: true,
index
});
options.api.push({
importName,
dedupe: true,
index
});
}
for (const [replacementIndex, token] of Object.keys(tokens).entries()) {
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
const localName = tokens[token];
importReplacements[token] = replacementName;
result.messages.push({
type: 'icss-replacement',
value: {
replacementName,
importName,
localName
}
options.replacements.push({
replacementName,
importName,
localName
});
}
}
@@ -81,18 +101,11 @@ var _default = _postcss.default.plugin('postcss-icss-parser', options => (css, r
(0, _icssUtils.replaceSymbols)(css, importReplacements);
}
const {
icssExports
} = extractedICSS;
for (const name of Object.keys(icssExports)) {
const value = (0, _icssUtils.replaceValueSymbols)(icssExports[name], importReplacements);
result.messages.push({
type: 'export',
value: {
name,
value
}
options.exports.push({
name,
value
});
}
});
+124 -51
View File
@@ -5,20 +5,20 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _util = require("util");
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
var _loaderUtils = require("loader-utils");
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-import-parser';
var _default = _postcss.default.plugin(pluginName, options => (css, result) => {
const importsMap = new Map();
function walkAtRules(css, result, options, callback) {
const accumulator = [];
css.walkAtRules(/^import$/i, atRule => {
// Convert only top-level @import
if (atRule.parent.type !== 'root') {
@@ -34,11 +34,11 @@ var _default = _postcss.default.plugin(pluginName, options => (css, result) => {
}
const {
nodes
nodes: paramsNodes
} = (0, _postcssValueParser.default)(atRule.params); // No nodes - `@import ;`
// Invalid type - `@import foo-bar;`
if (nodes.length === 0 || nodes[0].type !== 'string' && nodes[0].type !== 'function') {
if (paramsNodes.length === 0 || paramsNodes[0].type !== 'string' && paramsNodes[0].type !== 'function') {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule
});
@@ -48,20 +48,20 @@ var _default = _postcss.default.plugin(pluginName, options => (css, result) => {
let isStringValue;
let url;
if (nodes[0].type === 'string') {
if (paramsNodes[0].type === 'string') {
isStringValue = true;
url = nodes[0].value;
} else if (nodes[0].type === 'function') {
url = paramsNodes[0].value;
} else {
// Invalid function - `@import nourl(test.css);`
if (nodes[0].value.toLowerCase() !== 'url') {
if (paramsNodes[0].value.toLowerCase() !== 'url') {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule
});
return;
}
isStringValue = nodes[0].nodes.length !== 0 && nodes[0].nodes[0].type === 'string';
url = isStringValue ? nodes[0].nodes[0].value : _postcssValueParser.default.stringify(nodes[0].nodes);
isStringValue = paramsNodes[0].nodes.length !== 0 && paramsNodes[0].nodes[0].type === 'string';
url = isStringValue ? paramsNodes[0].nodes[0].value : _postcssValueParser.default.stringify(paramsNodes[0].nodes);
} // Empty url - `@import "";` or `@import url();`
@@ -72,70 +72,143 @@ var _default = _postcss.default.plugin(pluginName, options => (css, result) => {
return;
}
const isRequestable = (0, _loaderUtils.isUrlRequest)(url);
accumulator.push({
atRule,
url,
isStringValue,
mediaNodes: paramsNodes.slice(1)
});
});
callback(null, accumulator);
}
const asyncWalkAtRules = (0, _util.promisify)(walkAtRules);
var _default = _postcss.default.plugin(pluginName, options => async (css, result) => {
const parsedResults = await asyncWalkAtRules(css, result, options);
if (parsedResults.length === 0) {
return Promise.resolve();
}
const imports = new Map();
const tasks = [];
for (const parsedResult of parsedResults) {
const {
atRule,
url,
isStringValue,
mediaNodes
} = parsedResult;
let normalizedUrl = url;
let prefix = '';
const isRequestable = (0, _utils.isUrlRequestable)(normalizedUrl);
if (isRequestable) {
url = (0, _utils.normalizeUrl)(url, isStringValue); // Empty url after normalize - `@import '\
const queryParts = normalizedUrl.split('!');
if (queryParts.length > 1) {
normalizedUrl = queryParts.pop();
prefix = queryParts.join('!');
}
normalizedUrl = (0, _utils.normalizeUrl)(normalizedUrl, isStringValue); // Empty url after normalize - `@import '\
// \
// \
// ';
if (url.trim().length === 0) {
if (normalizedUrl.trim().length === 0) {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule
});
return;
}); // eslint-disable-next-line no-continue
continue;
}
}
const media = _postcssValueParser.default.stringify(nodes.slice(1)).trim().toLowerCase();
let media;
if (options.filter && !options.filter({
url,
media
})) {
return;
if (mediaNodes.length > 0) {
media = _postcssValueParser.default.stringify(mediaNodes).trim().toLowerCase();
}
if (options.filter && !options.filter(normalizedUrl, media)) {
// eslint-disable-next-line no-continue
continue;
}
atRule.remove();
if (isRequestable) {
const importKey = url;
let importName = importsMap.get(importKey);
const request = (0, _utils.requestify)(normalizedUrl, options.rootContext);
tasks.push((async () => {
const {
resolver,
context
} = options;
const resolvedUrl = await (0, _utils.resolveRequests)(resolver, context, [...new Set([request, normalizedUrl])]);
return {
url: resolvedUrl,
media,
prefix,
isRequestable
};
})());
} else {
tasks.push({
url,
media,
prefix,
isRequestable
});
}
}
const results = await Promise.all(tasks);
for (let index = 0; index <= results.length - 1; index++) {
const {
url,
isRequestable,
media
} = results[index];
if (isRequestable) {
const {
prefix
} = results[index];
const newUrl = prefix ? `${prefix}!${url}` : url;
const importKey = newUrl;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${importsMap.size}___`;
importsMap.set(importKey, importName);
result.messages.push({
type: 'import',
value: {
importName,
url: options.urlHandler ? options.urlHandler(url) : url
}
importName = `___CSS_LOADER_AT_RULE_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
options.imports.push({
importName,
url: options.urlHandler(newUrl),
index
});
}
result.messages.push({
type: 'api-import',
value: {
type: 'internal',
importName,
media
}
});
return;
options.api.push({
importName,
media,
index
}); // eslint-disable-next-line no-continue
continue;
}
result.messages.push({
pluginName,
type: 'api-import',
value: {
type: 'external',
url,
media
}
options.api.push({
url,
media,
index
});
});
}
return Promise.resolve();
});
exports.default = _default;
+204 -108
View File
@@ -5,6 +5,8 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var _util = require("util");
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
@@ -22,140 +24,234 @@ function getNodeFromUrlFunc(node) {
return node.nodes && node.nodes[0];
}
function walkUrls(parsed, callback) {
parsed.walk(node => {
if (node.type !== 'function') {
return;
}
function shouldHandleRule(rule, decl, result) {
// https://www.w3.org/TR/css-syntax-3/#typedef-url-token
if (rule.url.replace(/^[\s]+|[\s]+$/g, '').length === 0) {
result.warn(`Unable to find uri in '${decl.toString()}'`, {
node: decl
});
return false;
}
if (isUrlFunc.test(node.value)) {
const {
nodes
} = node;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
callback(getNodeFromUrlFunc(node), url, false, isStringValue); // Do not traverse inside `url`
// eslint-disable-next-line consistent-return
if (!(0, _utils.isUrlRequestable)(rule.url)) {
return false;
}
return false;
}
if (isImageSetFunc.test(node.value)) {
for (const nNode of node.nodes) {
const {
type,
value
} = nNode;
if (type === 'function' && isUrlFunc.test(value)) {
const {
nodes
} = nNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
callback(getNodeFromUrlFunc(nNode), url, false, isStringValue);
}
if (type === 'string') {
callback(nNode, value, true, true);
}
} // Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
return false;
}
});
return true;
}
var _default = _postcss.default.plugin(pluginName, options => (css, result) => {
const importsMap = new Map();
const replacementsMap = new Map();
let hasHelper = false;
function walkCss(css, result, options, callback) {
const accumulator = [];
css.walkDecls(decl => {
if (!needParseDecl.test(decl.value)) {
return;
}
const parsed = (0, _postcssValueParser.default)(decl.value);
walkUrls(parsed, (node, url, needQuotes, isStringValue) => {
// https://www.w3.org/TR/css-syntax-3/#typedef-url-token
if (url.replace(/^[\s]+|[\s]+$/g, '').length === 0) {
result.warn(`Unable to find uri in '${decl ? decl.toString() : decl.value}'`, {
node: decl
});
parsed.walk(node => {
if (node.type !== 'function') {
return;
}
if (options.filter && !options.filter(url)) {
return;
}
if (isUrlFunc.test(node.value)) {
const {
nodes
} = node;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
const rule = {
node: getNodeFromUrlFunc(node),
url,
needQuotes: false,
isStringValue
};
const splittedUrl = url.split(/(\?)?#/);
const [urlWithoutHash, singleQuery, hashValue] = splittedUrl;
const hash = singleQuery || hashValue ? `${singleQuery ? '?' : ''}${hashValue ? `#${hashValue}` : ''}` : '';
const normalizedUrl = (0, _utils.normalizeUrl)(urlWithoutHash, isStringValue);
const importKey = normalizedUrl;
let importName = importsMap.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${importsMap.size}___`;
importsMap.set(importKey, importName);
if (!hasHelper) {
const urlToHelper = require.resolve('../runtime/getUrl.js');
result.messages.push({
pluginName,
type: 'import',
value: {
importName: '___CSS_LOADER_GET_URL_IMPORT___',
url: options.urlHandler ? options.urlHandler(urlToHelper) : urlToHelper
}
if (shouldHandleRule(rule, decl, result)) {
accumulator.push({
decl,
rule,
parsed
});
hasHelper = true;
}
} // Do not traverse inside `url`
// eslint-disable-next-line consistent-return
result.messages.push({
pluginName,
type: 'import',
value: {
importName,
url: options.urlHandler ? options.urlHandler(normalizedUrl) : normalizedUrl
return false;
} else if (isImageSetFunc.test(node.value)) {
for (const nNode of node.nodes) {
const {
type,
value
} = nNode;
if (type === 'function' && isUrlFunc.test(value)) {
const {
nodes
} = nNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
const rule = {
node: getNodeFromUrlFunc(nNode),
url,
needQuotes: false,
isStringValue
};
if (shouldHandleRule(rule, decl, result)) {
accumulator.push({
decl,
rule,
parsed
});
}
} else if (type === 'string') {
const rule = {
node: nNode,
url: value,
needQuotes: true,
isStringValue: true
};
if (shouldHandleRule(rule, decl, result)) {
accumulator.push({
decl,
rule,
parsed
});
}
}
});
}
} // Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
const replacementKey = JSON.stringify({
importKey,
return false;
}
});
});
callback(null, accumulator);
}
const asyncWalkCss = (0, _util.promisify)(walkCss);
var _default = _postcss.default.plugin(pluginName, options => async (css, result) => {
const parsedResults = await asyncWalkCss(css, result, options);
if (parsedResults.length === 0) {
return Promise.resolve();
}
const tasks = [];
const imports = new Map();
const replacements = new Map();
let hasUrlImportHelper = false;
for (const parsedResult of parsedResults) {
const {
url,
isStringValue
} = parsedResult.rule;
let normalizedUrl = url;
let prefix = '';
const queryParts = normalizedUrl.split('!');
if (queryParts.length > 1) {
normalizedUrl = queryParts.pop();
prefix = queryParts.join('!');
}
normalizedUrl = (0, _utils.normalizeUrl)(normalizedUrl, isStringValue);
if (!options.filter(normalizedUrl)) {
// eslint-disable-next-line no-continue
continue;
}
if (!hasUrlImportHelper) {
options.imports.push({
importName: '___CSS_LOADER_GET_URL_IMPORT___',
url: options.urlHandler(require.resolve('../runtime/getUrl.js')),
index: -1
});
hasUrlImportHelper = true;
}
const splittedUrl = normalizedUrl.split(/(\?)?#/);
const [pathname, query, hashOrQuery] = splittedUrl;
let hash = query ? '?' : '';
hash += hashOrQuery ? `#${hashOrQuery}` : '';
const request = (0, _utils.requestify)(pathname, options.rootContext);
tasks.push((async () => {
const {
resolver,
context
} = options;
const resolvedUrl = await (0, _utils.resolveRequests)(resolver, context, [...new Set([request, normalizedUrl])]);
return {
url: resolvedUrl,
prefix,
hash,
parsedResult
};
})());
}
const results = await Promise.all(tasks);
for (let index = 0; index <= results.length - 1; index++) {
const {
url,
prefix,
hash,
parsedResult: {
decl,
rule,
parsed
}
} = results[index];
const newUrl = prefix ? `${prefix}!${url}` : url;
const importKey = newUrl;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
options.imports.push({
importName,
url: options.urlHandler(newUrl),
index
});
}
const {
needQuotes
} = rule;
const replacementKey = JSON.stringify({
newUrl,
hash,
needQuotes
});
let replacementName = replacements.get(replacementKey);
if (!replacementName) {
replacementName = `___CSS_LOADER_URL_REPLACEMENT_${replacements.size}___`;
replacements.set(replacementKey, replacementName);
options.replacements.push({
replacementName,
importName,
hash,
needQuotes
});
let replacementName = replacementsMap.get(replacementKey);
if (!replacementName) {
replacementName = `___CSS_LOADER_URL_REPLACEMENT_${replacementsMap.size}___`;
replacementsMap.set(replacementKey, replacementName);
result.messages.push({
pluginName,
type: 'url-replacement',
value: {
replacementName,
importName,
hash,
needQuotes
}
});
} // eslint-disable-next-line no-param-reassign
} // eslint-disable-next-line no-param-reassign
node.type = 'word'; // eslint-disable-next-line no-param-reassign
rule.node.type = 'word'; // eslint-disable-next-line no-param-reassign
node.value = replacementName;
}); // eslint-disable-next-line no-param-reassign
rule.node.value = replacementName; // eslint-disable-next-line no-param-reassign
decl.value = parsed.toString();
});
}
return Promise.resolve();
});
exports.default = _default;
+370 -140
View File
@@ -3,22 +3,31 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.normalizeOptions = normalizeOptions;
exports.shouldUseModulesPlugins = shouldUseModulesPlugins;
exports.shouldUseImportPlugin = shouldUseImportPlugin;
exports.shouldUseURLPlugin = shouldUseURLPlugin;
exports.shouldUseIcssPlugin = shouldUseIcssPlugin;
exports.normalizeUrl = normalizeUrl;
exports.requestify = requestify;
exports.getFilter = getFilter;
exports.getModulesOptions = getModulesOptions;
exports.getModulesPlugins = getModulesPlugins;
exports.normalizeSourceMap = normalizeSourceMap;
exports.getPreRequester = getPreRequester;
exports.getImportCode = getImportCode;
exports.getModuleCode = getModuleCode;
exports.getExportCode = getExportCode;
exports.shouldUseModulesPlugins = shouldUseModulesPlugins;
exports.resolveRequests = resolveRequests;
exports.isUrlRequestable = isUrlRequestable;
exports.sort = sort;
var _url = require("url");
var _path = _interopRequireDefault(require("path"));
var _loaderUtils = require("loader-utils");
var _normalizePath = _interopRequireDefault(require("normalize-path"));
var _cssesc = _interopRequireDefault(require("cssesc"));
var _postcssModulesValues = _interopRequireDefault(require("postcss-modules-values"));
@@ -39,6 +48,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
const whitespace = '[\\x20\\t\\r\\n\\f]';
const unescapeRegExp = new RegExp(`\\\\([\\da-f]{1,6}${whitespace}?|(${whitespace})|.)`, 'ig');
const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;
function unescape(str) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
@@ -54,127 +64,226 @@ function unescape(str) {
String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
/* eslint-enable line-comment-position */
});
}
function normalizePath(file) {
return _path.default.sep === '\\' ? file.replace(/\\/g, '/') : file;
} // eslint-disable-next-line no-control-regex
const filenameReservedRegex = /[<>:"/\\|?*\x00-\x1F]/g; // eslint-disable-next-line no-control-regex
const filenameReservedRegex = /[<>:"/\\|?*]/g; // eslint-disable-next-line no-control-regex
const reControlChars = /[\u0000-\u001f\u0080-\u009f]/g;
const reRelativePath = /^\.+/;
function getLocalIdent(loaderContext, localIdentName, localName, options) {
if (!options.context) {
// eslint-disable-next-line no-param-reassign
options.context = loaderContext.rootContext;
}
function defaultGetLocalIdent(loaderContext, localIdentName, localName, options) {
const {
context,
hashPrefix
} = options;
const {
resourcePath
} = loaderContext;
const request = normalizePath(_path.default.relative(context, resourcePath)); // eslint-disable-next-line no-param-reassign
const request = (0, _normalizePath.default)(_path.default.relative(options.context || '', loaderContext.resourcePath)); // eslint-disable-next-line no-param-reassign
options.content = `${options.hashPrefix + request}+${unescape(localName)}`; // Using `[path]` placeholder outputs `/` we need escape their
options.content = `${hashPrefix + request}\x00${unescape(localName)}`; // Using `[path]` placeholder outputs `/` we need escape their
// Also directories can contains invalid characters for css we need escape their too
return (0, _cssesc.default)((0, _loaderUtils.interpolateName)(loaderContext, localIdentName, options) // For `[hash]` placeholder
.replace(/^((-?[0-9])|--)/, '_$1').replace(filenameReservedRegex, '-').replace(reControlChars, '-').replace(reRelativePath, '-').replace(/\./g, '-'), {
.replace(/^((-?[0-9])|--)/, '_$1').replace(filenameReservedRegex, '-').replace(reControlChars, '-').replace(/\./g, '-'), {
isIdentifier: true
}).replace(/\\\[local\\\]/gi, localName);
}).replace(/\\\[local\\]/gi, localName);
}
function normalizeUrl(url, isStringValue) {
let normalizedUrl = url;
if (isStringValue && /\\[\n]/.test(normalizedUrl)) {
normalizedUrl = normalizedUrl.replace(/\\[\n]/g, '');
if (isStringValue && /\\(\n|\r\n|\r|\f)/.test(normalizedUrl)) {
normalizedUrl = normalizedUrl.replace(/\\(\n|\r\n|\r|\f)/g, '');
}
return (0, _loaderUtils.urlToRequest)(decodeURIComponent(unescape(normalizedUrl)));
if (matchNativeWin32Path.test(url)) {
return decodeURIComponent(normalizedUrl);
}
return decodeURIComponent(unescape(normalizedUrl));
}
function getFilter(filter, resourcePath, defaultFilter = null) {
return item => {
if (defaultFilter && !defaultFilter(item)) {
return false;
}
function requestify(url, rootContext) {
if (/^file:/i.test(url)) {
return (0, _url.fileURLToPath)(url);
}
return url.charAt(0) === '/' ? (0, _loaderUtils.urlToRequest)(url, rootContext) : (0, _loaderUtils.urlToRequest)(url);
}
function getFilter(filter, resourcePath) {
return (...args) => {
if (typeof filter === 'function') {
return filter(item, resourcePath);
return filter(...args, resourcePath);
}
return true;
};
}
function shouldUseModulesPlugins(modules, resourcePath) {
if (typeof modules === 'undefined') {
const moduleRegExp = /\.module\.\w+$/i;
function getModulesOptions(rawOptions, loaderContext) {
const {
resourcePath
} = loaderContext;
if (typeof rawOptions.modules === 'undefined') {
const isModules = moduleRegExp.test(resourcePath);
if (!isModules) {
return false;
}
} else if (typeof rawOptions.modules === 'boolean' && rawOptions.modules === false) {
return false;
}
if (typeof modules === 'boolean') {
return modules;
}
if (typeof modules === 'string') {
return true;
}
if (typeof modules.auto === 'boolean') {
return modules.auto ? /\.module\.\w+$/i.test(resourcePath) : false;
}
if (modules.auto instanceof RegExp) {
return modules.auto.test(resourcePath);
}
if (typeof modules.auto === 'function') {
return modules.auto(resourcePath);
}
return true;
}
function getModulesPlugins(options, loaderContext) {
let modulesOptions = {
compileType: rawOptions.icss ? 'icss' : 'module',
auto: true,
mode: 'local',
exportGlobals: false,
localIdentName: '[hash:base64]',
getLocalIdent,
hashPrefix: '',
localIdentRegExp: null
localIdentContext: loaderContext.rootContext,
localIdentHashPrefix: '',
// eslint-disable-next-line no-undefined
localIdentRegExp: undefined,
getLocalIdent: defaultGetLocalIdent,
namedExport: false,
exportLocalsConvention: 'asIs',
exportOnlyLocals: false
};
if (typeof options.modules === 'boolean' || typeof options.modules === 'string') {
modulesOptions.mode = typeof options.modules === 'string' ? options.modules : 'local';
if (typeof rawOptions.modules === 'boolean' || typeof rawOptions.modules === 'string') {
modulesOptions.mode = typeof rawOptions.modules === 'string' ? rawOptions.modules : 'local';
} else {
modulesOptions = Object.assign({}, modulesOptions, options.modules);
if (rawOptions.modules) {
if (typeof rawOptions.modules.auto === 'boolean') {
const isModules = rawOptions.modules.auto && moduleRegExp.test(resourcePath);
if (!isModules) {
return false;
}
} else if (rawOptions.modules.auto instanceof RegExp) {
const isModules = rawOptions.modules.auto.test(resourcePath);
if (!isModules) {
return false;
}
} else if (typeof rawOptions.modules.auto === 'function') {
const isModule = rawOptions.modules.auto(resourcePath);
if (!isModule) {
return false;
}
}
if (rawOptions.modules.namedExport === true && typeof rawOptions.modules.exportLocalsConvention === 'undefined') {
modulesOptions.exportLocalsConvention = 'camelCaseOnly';
}
}
modulesOptions = { ...modulesOptions,
...(rawOptions.modules || {})
};
}
if (typeof modulesOptions.mode === 'function') {
modulesOptions.mode = modulesOptions.mode(loaderContext.resourcePath);
}
if (modulesOptions.namedExport === true) {
if (rawOptions.esModule === false) {
throw new Error('The "modules.namedExport" option requires the "esModules" option to be enabled');
}
if (modulesOptions.exportLocalsConvention !== 'camelCaseOnly') {
throw new Error('The "modules.namedExport" option requires the "modules.exportLocalsConvention" option to be "camelCaseOnly"');
}
}
return modulesOptions;
}
function normalizeOptions(rawOptions, loaderContext) {
if (rawOptions.icss) {
loaderContext.emitWarning(new Error('The "icss" option is deprecated, use "modules.compileType: "icss"" instead'));
}
const modulesOptions = getModulesOptions(rawOptions, loaderContext);
return {
url: typeof rawOptions.url === 'undefined' ? true : rawOptions.url,
import: typeof rawOptions.import === 'undefined' ? true : rawOptions.import,
modules: modulesOptions,
// TODO remove in the next major release
icss: typeof rawOptions.icss === 'undefined' ? false : rawOptions.icss,
sourceMap: typeof rawOptions.sourceMap === 'boolean' ? rawOptions.sourceMap : loaderContext.sourceMap,
importLoaders: typeof rawOptions.importLoaders === 'string' ? parseInt(rawOptions.importLoaders, 10) : rawOptions.importLoaders,
esModule: typeof rawOptions.esModule === 'undefined' ? true : rawOptions.esModule
};
}
function shouldUseImportPlugin(options) {
if (options.modules.exportOnlyLocals) {
return false;
}
if (typeof options.import === 'boolean') {
return options.import;
}
return true;
}
function shouldUseURLPlugin(options) {
if (options.modules.exportOnlyLocals) {
return false;
}
if (typeof options.url === 'boolean') {
return options.url;
}
return true;
}
function shouldUseModulesPlugins(options) {
return options.modules.compileType === 'module';
}
function shouldUseIcssPlugin(options) {
return options.icss === true || Boolean(options.modules);
}
function getModulesPlugins(options, loaderContext) {
const {
mode,
getLocalIdent,
localIdentName,
localIdentContext,
localIdentHashPrefix,
localIdentRegExp
} = options.modules;
let plugins = [];
try {
plugins = [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
mode: modulesOptions.mode
mode
}), (0, _postcssModulesExtractImports.default)(), (0, _postcssModulesScope.default)({
generateScopedName: function generateScopedName(exportName) {
let localIdent = modulesOptions.getLocalIdent(loaderContext, modulesOptions.localIdentName, exportName, {
context: modulesOptions.context,
hashPrefix: modulesOptions.hashPrefix,
regExp: modulesOptions.localIdentRegExp
generateScopedName(exportName) {
return getLocalIdent(loaderContext, localIdentName, exportName, {
context: localIdentContext,
hashPrefix: localIdentHashPrefix,
regExp: localIdentRegExp
});
if (!localIdent) {
localIdent = getLocalIdent(loaderContext, modulesOptions.localIdentName, exportName, {
context: modulesOptions.context,
hashPrefix: modulesOptions.hashPrefix,
regExp: modulesOptions.localIdentRegExp
});
}
return localIdent;
},
exportGlobals: modulesOptions.exportGlobals
exportGlobals: options.modules.exportGlobals
})];
} catch (error) {
loaderContext.emitError(error);
@@ -183,26 +292,57 @@ function getModulesPlugins(options, loaderContext) {
return plugins;
}
function normalizeSourceMap(map) {
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
function getURLType(source) {
if (source[0] === '/') {
if (source[1] === '/') {
return 'scheme-relative';
}
return 'path-absolute';
}
if (IS_NATIVE_WIN32_PATH.test(source)) {
return 'path-absolute';
}
return ABSOLUTE_SCHEME.test(source) ? 'absolute' : 'path-relative';
}
function normalizeSourceMap(map, resourcePath) {
let newMap = map; // Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof newMap === 'string') {
newMap = JSON.parse(newMap);
} // Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
// We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
if (newMap.file) {
newMap.file = (0, _normalizePath.default)(newMap.file);
}
if (newMap.sourceRoot) {
newMap.sourceRoot = (0, _normalizePath.default)(newMap.sourceRoot);
}
delete newMap.file;
const {
sourceRoot
} = newMap;
delete newMap.sourceRoot;
if (newMap.sources) {
newMap.sources = newMap.sources.map(source => (0, _normalizePath.default)(source));
// Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
// We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
newMap.sources = newMap.sources.map(source => {
// Non-standard syntax from `postcss`
if (source.indexOf('<') === 0) {
return source;
}
const sourceType = getURLType(source); // Do no touch `scheme-relative` and `absolute` URLs
if (sourceType === 'path-relative' || sourceType === 'path-absolute') {
const absoluteSource = sourceType === 'path-relative' && sourceRoot ? _path.default.resolve(sourceRoot, normalizePath(source)) : normalizePath(source);
return _path.default.relative(_path.default.dirname(resourcePath), absoluteSource);
}
return source;
});
}
return newMap;
@@ -229,94 +369,127 @@ function getPreRequester({
};
}
function getImportCode(loaderContext, exportType, imports, esModule) {
function getImportCode(imports, options) {
let code = '';
if (exportType === 'full') {
const apiUrl = (0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/api'));
code += esModule ? `import ___CSS_LOADER_API_IMPORT___ from ${apiUrl};\n` : `var ___CSS_LOADER_API_IMPORT___ = require(${apiUrl});\n`;
}
for (const item of imports) {
const {
importName,
url
url,
icss
} = item;
code += esModule ? `import ${importName} from ${url};\n` : `var ${importName} = require(${url});\n`;
if (options.esModule) {
if (icss && options.modules.namedExport) {
code += `import ${options.modules.exportOnlyLocals ? '' : `${importName}, `}* as ${importName}_NAMED___ from ${url};\n`;
} else {
code += `import ${importName} from ${url};\n`;
}
} else {
code += `var ${importName} = require(${url});\n`;
}
}
return code ? `// Imports\n${code}` : '';
}
function getModuleCode(result, exportType, sourceMap, apiImports, urlReplacements, icssReplacements, esModule) {
if (exportType !== 'full') {
function normalizeSourceMapForRuntime(map, loaderContext) {
const resultMap = map ? map.toJSON() : null;
if (resultMap) {
delete resultMap.file;
resultMap.sourceRoot = '';
resultMap.sources = resultMap.sources.map(source => {
// Non-standard syntax from `postcss`
if (source.indexOf('<') === 0) {
return source;
}
const sourceType = getURLType(source);
if (sourceType !== 'path-relative') {
return source;
}
const resourceDirname = _path.default.dirname(loaderContext.resourcePath);
const absoluteSource = _path.default.resolve(resourceDirname, source);
const contextifyPath = normalizePath(_path.default.relative(loaderContext.rootContext, absoluteSource));
return `webpack://${contextifyPath}`;
});
}
return JSON.stringify(resultMap);
}
function getModuleCode(result, api, replacements, options, loaderContext) {
if (options.modules.exportOnlyLocals === true) {
return '';
}
const {
css,
map
} = result;
const sourceMapValue = sourceMap && map ? `,${map}` : '';
let code = JSON.stringify(css);
let beforeCode = '';
beforeCode += esModule ? `var exports = ___CSS_LOADER_API_IMPORT___(${sourceMap});\n` : `exports = ___CSS_LOADER_API_IMPORT___(${sourceMap});\n`;
const sourceMapValue = options.sourceMap ? `,${normalizeSourceMapForRuntime(result.map, loaderContext)}` : '';
let code = JSON.stringify(result.css);
let beforeCode = `var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(${options.sourceMap});\n`;
for (const item of apiImports) {
for (const item of api) {
const {
type,
url,
media,
dedupe
} = item;
beforeCode += type === 'internal' ? `exports.i(${item.importName}${media ? `, ${JSON.stringify(media)}` : dedupe ? ', ""' : ''}${dedupe ? ', true' : ''});\n` : `exports.push([module.id, ${JSON.stringify(`@import url(${item.url});`)}${media ? `, ${JSON.stringify(media)}` : ''}]);\n`;
beforeCode += url ? `___CSS_LOADER_EXPORT___.push([module.id, ${JSON.stringify(`@import url(${url});`)}${media ? `, ${JSON.stringify(media)}` : ''}]);\n` : `___CSS_LOADER_EXPORT___.i(${item.importName}${media ? `, ${JSON.stringify(media)}` : dedupe ? ', ""' : ''}${dedupe ? ', true' : ''});\n`;
}
for (const item of urlReplacements) {
const {
replacementName,
importName,
hash,
needQuotes
} = item;
const getUrlOptions = [].concat(hash ? [`hash: ${JSON.stringify(hash)}`] : []).concat(needQuotes ? 'needQuotes: true' : []);
const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : '';
beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\n`;
code = code.replace(new RegExp(replacementName, 'g'), () => `" + ${replacementName} + "`);
}
for (const replacement of icssReplacements) {
for (const item of replacements) {
const {
replacementName,
importName,
localName
} = replacement;
code = code.replace(new RegExp(replacementName, 'g'), () => `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
} = item;
if (localName) {
code = code.replace(new RegExp(replacementName, 'g'), () => options.modules.namedExport ? `" + ${importName}_NAMED___[${JSON.stringify((0, _camelcase.default)(localName))}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
} else {
const {
hash,
needQuotes
} = item;
const getUrlOptions = [].concat(hash ? [`hash: ${JSON.stringify(hash)}`] : []).concat(needQuotes ? 'needQuotes: true' : []);
const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : '';
beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\n`;
code = code.replace(new RegExp(replacementName, 'g'), () => `" + ${replacementName} + "`);
}
}
return `${beforeCode}// Module\nexports.push([module.id, ${code}, ""${sourceMapValue}]);\n`;
return `${beforeCode}// Module\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, ""${sourceMapValue}]);\n`;
}
function dashesCamelCase(str) {
return str.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase());
}
function getExportCode(exports, exportType, localsConvention, icssReplacements, esModule) {
let code = '';
function getExportCode(exports, replacements, options) {
let code = '// Exports\n';
let localsCode = '';
const addExportToLocalsCode = (name, value) => {
if (localsCode) {
localsCode += `,\n`;
}
if (options.modules.namedExport) {
localsCode += `export const ${(0, _camelcase.default)(name)} = ${JSON.stringify(value)};\n`;
} else {
if (localsCode) {
localsCode += `,\n`;
}
localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
}
};
for (const {
name,
value
} of exports) {
switch (localsConvention) {
switch (options.modules.exportLocalsConvention) {
case 'camelCase':
{
addExportToLocalsCode(name, value);
@@ -360,24 +533,81 @@ function getExportCode(exports, exportType, localsConvention, icssReplacements,
}
}
for (const replacement of icssReplacements) {
for (const item of replacements) {
const {
replacementName,
importName,
localName
} = replacement;
localsCode = localsCode.replace(new RegExp(replacementName, 'g'), () => exportType === 'locals' ? `" + ${importName}[${JSON.stringify(localName)}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
} = item;
if (localName) {
const {
importName
} = item;
localsCode = localsCode.replace(new RegExp(replacementName, 'g'), () => {
if (options.modules.namedExport) {
return `" + ${importName}_NAMED___[${JSON.stringify((0, _camelcase.default)(localName))}] + "`;
} else if (options.modules.exportOnlyLocals) {
return `" + ${importName}[${JSON.stringify(localName)}] + "`;
}
return `" + ${importName}.locals[${JSON.stringify(localName)}] + "`;
});
} else {
localsCode = localsCode.replace(new RegExp(replacementName, 'g'), () => `" + ${replacementName} + "`);
}
}
if (exportType === 'locals') {
code += `${esModule ? 'export default' : 'module.exports ='} ${localsCode ? `{\n${localsCode}\n}` : '{}'};\n`;
} else {
if (localsCode) {
code += `exports.locals = {\n${localsCode}\n};\n`;
if (options.modules.exportOnlyLocals) {
code += options.modules.namedExport ? localsCode : `${options.esModule ? 'export default' : 'module.exports ='} {\n${localsCode}\n};\n`;
return code;
}
if (localsCode) {
code += options.modules.namedExport ? localsCode : `___CSS_LOADER_EXPORT___.locals = {\n${localsCode}\n};\n`;
}
code += `${options.esModule ? 'export default' : 'module.exports ='} ___CSS_LOADER_EXPORT___;\n`;
return code;
}
async function resolveRequests(resolve, context, possibleRequests) {
return resolve(context, possibleRequests[0]).then(result => {
return result;
}).catch(error => {
const [, ...tailPossibleRequests] = possibleRequests;
if (tailPossibleRequests.length === 0) {
throw error;
}
code += `${esModule ? 'export default' : 'module.exports ='} exports;\n`;
return resolveRequests(resolve, context, tailPossibleRequests);
});
}
function isUrlRequestable(url) {
// Protocol-relative URLs
if (/^\/\//.test(url)) {
return false;
} // `file:` protocol
if (/^file:/i.test(url)) {
return true;
} // Absolute URLs
if (/^[a-z][a-z0-9+.-]*:/i.test(url) && !matchNativeWin32Path.test(url)) {
return false;
} // `#` URLs
if (/^#/.test(url)) {
return false;
}
return `// Exports\n${code}`;
return true;
}
function sort(a, b) {
return a.index - b.index;
}