Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: respected style field from package.json #1099

Merged
merged 7 commits into from Jul 7, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -16,3 +16,4 @@ Thumbs.db
.vscode
*.sublime-project
*.sublime-workspace
/test/fixtures/import/import-absolute.css
29 changes: 28 additions & 1 deletion src/index.js
Expand Up @@ -21,6 +21,7 @@ import {
getModulesPlugins,
normalizeSourceMap,
shouldUseModulesPlugins,
sortByName,
} from './utils';

export default function loader(content, map, meta) {
Expand All @@ -47,9 +48,19 @@ export default function loader(content, map, meta) {
plugins.push(icssParser({ urlHandler }));

if (options.import !== false && exportType === 'full') {
const resolver = this.getResolve({
mainFields: ['css', 'style', 'main', '...'],
mainFiles: ['index', '...'],
extensions: ['.css'],
restrictions: [/\.css$/i],
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This restriction broke @import for files with an extension other than .css (#1164). Can we remove it (#1165)?

});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

conditionNames: ['style'],


plugins.push(
importParser({
context: this.context,
rootContext: this.rootContext,
filter: getFilter(options.import, this.resourcePath),
resolver,
urlHandler,
})
);
Expand Down Expand Up @@ -125,11 +136,27 @@ export default function loader(content, map, meta) {
}
}

imports.sort((a, b) => a.index - b.index);
apiImports.sort((a, b) => a.index - b.index);

const sortedImports = sortByName(imports, [
'CSS_LOADER_ICSS_IMPORT',
'CSS_LOADER_AT_RULE_IMPORT',
'CSS_LOADER_GET_URL_IMPORT',
'CSS_LOADER_URL_IMPORT',
'CSS_LOADER_URL_REPLACEMENT',
]);

const { localsConvention } = options;
const esModule =
typeof options.esModule !== 'undefined' ? options.esModule : false;

const importCode = getImportCode(this, exportType, imports, esModule);
const importCode = getImportCode(
this,
exportType,
sortedImports,
esModule
);
const moduleCode = getModuleCode(
result,
exportType,
Expand Down
242 changes: 147 additions & 95 deletions src/plugins/postcss-import-parser.js
@@ -1,132 +1,184 @@
import postcss from 'postcss';
import valueParser from 'postcss-value-parser';
import { isUrlRequest } from 'loader-utils';
import { isUrlRequest, urlToRequest } from 'loader-utils';

import { normalizeUrl } from '../utils';
import { normalizeUrl, resolveRequests } from '../utils';

const pluginName = 'postcss-import-parser';

export default postcss.plugin(pluginName, (options) => (css, result) => {
const importsMap = new Map();

css.walkAtRules(/^import$/i, (atRule) => {
// Convert only top-level @import
if (atRule.parent.type !== 'root') {
return;
}

// Nodes do not exists - `@import url('http://') :root {}`
if (atRule.nodes) {
result.warn(
"It looks like you didn't end your @import statement correctly. Child nodes are attached to it.",
{ node: atRule }
);
return new Promise((resolve, reject) => {
const importsMap = new Map();
const tasks = [];

return;
}

const { nodes } = valueParser(atRule.params);

// No nodes - `@import ;`
// Invalid type - `@import foo-bar;`
if (
nodes.length === 0 ||
(nodes[0].type !== 'string' && nodes[0].type !== 'function')
) {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule,
});

return;
}

let isStringValue;
let url;

if (nodes[0].type === 'string') {
isStringValue = true;
url = nodes[0].value;
} else if (nodes[0].type === 'function') {
// Invalid function - `@import nourl(test.css);`
if (nodes[0].value.toLowerCase() !== 'url') {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule,
});
// A counter is used instead of an index in callback css.walkAtRules because we mutate AST (atRule.remove())
let index = 0;

css.walkAtRules(/^import$/i, (atRule) => {
// Convert only top-level @import
if (atRule.parent.type !== 'root') {
return;
}

isStringValue =
nodes[0].nodes.length !== 0 && nodes[0].nodes[0].type === 'string';
url = isStringValue
? nodes[0].nodes[0].value
: valueParser.stringify(nodes[0].nodes);
}
// Nodes do not exists - `@import url('http://') :root {}`
if (atRule.nodes) {
result.warn(
"It looks like you didn't end your @import statement correctly. Child nodes are attached to it.",
{ node: atRule }
);

// Empty url - `@import "";` or `@import url();`
if (url.trim().length === 0) {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule,
});
return;
}

return;
}
const { nodes } = valueParser(atRule.params);

const isRequestable = isUrlRequest(url);
// No nodes - `@import ;`
// Invalid type - `@import foo-bar;`
if (
nodes.length === 0 ||
(nodes[0].type !== 'string' && nodes[0].type !== 'function')
) {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule,
});

if (isRequestable) {
url = normalizeUrl(url, isStringValue);
return;
}

let isStringValue;
let url;

if (nodes[0].type === 'string') {
isStringValue = true;
url = nodes[0].value;
} else if (nodes[0].type === 'function') {
// Invalid function - `@import nourl(test.css);`
if (nodes[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
: valueParser.stringify(nodes[0].nodes);
}

// Empty url after normalize - `@import '\
// \
// \
// ';
// Empty url - `@import "";` or `@import url();`
if (url.trim().length === 0) {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule,
});

return;
}
}

const media = valueParser.stringify(nodes.slice(1)).trim().toLowerCase();
let request;

if (options.filter && !options.filter({ url, media })) {
return;
}
// May be url is server-relative url, but not //example.com
if (url.charAt(0) === '/' && url.charAt(1) !== '/') {
request = urlToRequest(url, options.rootContext);
}

atRule.remove();
const isRequestable = isUrlRequest(url);

if (isRequestable) {
const importKey = url;
let importName = importsMap.get(importKey);
if (isRequestable) {
url = normalizeUrl(url, isStringValue);

if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${importsMap.size}___`;
importsMap.set(importKey, importName);
// Empty url after normalize - `@import '\
// \
// \
// ';
if (url.trim().length === 0) {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule,
});

result.messages.push({
type: 'import',
value: {
importName,
url: options.urlHandler ? options.urlHandler(url) : url,
},
});
return;
}
}

result.messages.push({
type: 'api-import',
value: { type: 'internal', importName, media },
});
const media = valueParser.stringify(nodes.slice(1)).trim().toLowerCase();

return;
}
if (options.filter && !options.filter({ url, media })) {
return;
}

result.messages.push({
pluginName,
type: 'api-import',
value: { type: 'external', url, media },
atRule.remove();

index += 1;

tasks.push(
Promise.resolve(index).then(async (currentIndex) => {
if (isRequestable || request) {
const importKey = url;
let importName = importsMap.get(importKey);

if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${importsMap.size}___`;
importsMap.set(importKey, importName);

const { resolver, context } = options;

const possibleRequest = [url];

if (request) {
possibleRequest.push(request);
}

let resolvedUrl;

try {
resolvedUrl = await resolveRequests(
resolver,
context,
possibleRequest
);
} catch (error) {
throw error;
}

result.messages.push({
type: 'import',
value: {
importName,
url: options.urlHandler
? options.urlHandler(resolvedUrl)
: resolvedUrl,
index: currentIndex,
},
});
}

result.messages.push({
type: 'api-import',
value: {
type: 'internal',
importName,
media,
index: currentIndex,
},
});

return;
}

result.messages.push({
pluginName,
type: 'api-import',
value: { type: 'external', url, media, index: currentIndex },
});
})
);
});

Promise.all(tasks).then(
() => resolve(),
(error) => reject(error)
);
});
});
8 changes: 7 additions & 1 deletion src/plugins/postcss-url-parser.js
Expand Up @@ -65,6 +65,8 @@ export default postcss.plugin(pluginName, (options) => (css, result) => {

let hasHelper = false;

let index = 0;

css.walkDecls((decl) => {
if (!needParseDecl.test(decl.value)) {
return;
Expand Down Expand Up @@ -99,6 +101,8 @@ export default postcss.plugin(pluginName, (options) => (css, result) => {
const importKey = normalizedUrl;
let importName = importsMap.get(importKey);

index += 1;

if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${importsMap.size}___`;
importsMap.set(importKey, importName);
Expand All @@ -114,6 +118,7 @@ export default postcss.plugin(pluginName, (options) => (css, result) => {
url: options.urlHandler
? options.urlHandler(urlToHelper)
: urlToHelper,
index,
},
});

Expand All @@ -128,6 +133,7 @@ export default postcss.plugin(pluginName, (options) => (css, result) => {
url: options.urlHandler
? options.urlHandler(normalizedUrl)
: normalizedUrl,
index,
},
});
}
Expand All @@ -142,7 +148,7 @@ export default postcss.plugin(pluginName, (options) => (css, result) => {
result.messages.push({
pluginName,
type: 'url-replacement',
value: { replacementName, importName, hash, needQuotes },
value: { replacementName, importName, hash, needQuotes, index },
});
}

Expand Down