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

feat(css-extract): add defaultExport and namedExport support #6657

Merged
merged 1 commit into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/rspack/etc/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1570,6 +1570,8 @@ const cssChunkFilename: z.ZodUnion<[z.ZodString, z.ZodFunction<z.ZodTuple<[z.Zod

// @public (undocumented)
export interface CssExtractRspackLoaderOptions {
// (undocumented)
defaultExport?: boolean;
// (undocumented)
emit?: boolean;
// (undocumented)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
},
"layer": {
"type": "string"
},
"defaultExport": {
"type": "boolean",
"description": "Duplicate the named export with CSS modules locals to the default export (only when `esModules: true` for css-loader).",
"link": "https://github.com/webpack-contrib/mini-css-extract-plugin#defaultexports"
}
}
}
56 changes: 44 additions & 12 deletions packages/rspack/src/builtin-plugin/css-extract/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export interface CssExtractRspackLoaderOptions {

// TODO: support layer
layer?: boolean;
defaultExport?: boolean;
}

function hotLoader(
Expand Down Expand Up @@ -199,22 +200,53 @@ export const pitch: LoaderDefinition["pitch"] = function (request, _, data) {
return;
}

const result = locals!
? namedExport
? Object.keys(locals)
const result = (function makeResult() {
if (locals!) {
if (namedExport) {
const identifiers = Array.from(
(function* generateIdentifiers() {
let identifierId = 0;

for (const key of Object.keys(locals)) {
identifierId += 1;

yield [`_${identifierId.toString(16)}`, key];
}
})()
);

const localsString = identifiers
.map(
key =>
`\nexport var ${key} = ${stringifyLocal(
([id, key]) =>
`\nvar ${id} = ${stringifyLocal(
/** @type {Locals} */ locals[key]
)};`
)
.join("")
: `\n${
esModule ? "export default" : "module.exports ="
} ${JSON.stringify(locals)};`
: esModule
? `\nexport {};`
: "";
.join("");
const exportsString = `export { ${identifiers
.map(([id, key]) => `${id} as ${JSON.stringify(key)}`)
.join(", ")} }`;

const defaultExport =
typeof options.defaultExport !== "undefined"
? options.defaultExport
: false;

return defaultExport
? `${localsString}\n${exportsString}\nexport default { ${identifiers
.map(([id, key]) => `${JSON.stringify(key)}: ${id}`)
.join(", ")} }\n`
: `${localsString}\n${exportsString}\n`;
}

return `\n${
esModule ? "export default" : "module.exports = "
} ${JSON.stringify(locals)};`;
} else if (esModule) {
return "\nexport {};";
}
return "";
})();

let resultSource = `// extracted by ${CssExtractRspackPlugin.pluginName}`;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ var __webpack_modules__ = ({
"./style.css?3e20": (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
cnA: function() { return cnA; },
cnB: function() { return cnB; }
cnA: function() { return _1; },
cnB: function() { return _2; }
});
// extracted by css-extract-rspack-plugin
var cnA = ()=>"class-name-a";
var cnB = ()=>"class-name-b";
var _1 = ()=>"class-name-a";
var _2 = ()=>"class-name-b";

}),

});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.Xh041yLR4iCP4RGjge50 {
background: red;
}

.NMuRsxoDwvW8BhSXhFAY {
color: green;
}

.ayWIv09rPsAqE2JznIsI {
color: blue;
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
var __webpack_modules__ = ({
"./style.css?eccb": (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
"a-class": function() { return _1; },
b__class: function() { return _2; },
cClass: function() { return _3; }
});
// extracted by css-extract-rspack-plugin
var _1 = "Xh041yLR4iCP4RGjge50";
var _2 = "NMuRsxoDwvW8BhSXhFAY";
var _3 = "ayWIv09rPsAqE2JznIsI";

}),

});
/************************************************************************/
// The module cache
var __webpack_module_cache__ = {};

// The require function
function __webpack_require__(moduleId) {

// Check if module is in cache
var cachedModule = __webpack_module_cache__[moduleId];
if (cachedModule !== undefined) {
return cachedModule.exports;
}
// Create a new module (and put it into the cache)
var module = (__webpack_module_cache__[moduleId] = {
exports: {}
});
// Execute the module function
__webpack_modules__[moduleId](module, module.exports, __webpack_require__);

// Return the exports of the module
return module.exports;

}

/************************************************************************/
// webpack/runtime/define_property_getters
(() => {
__webpack_require__.d = function(exports, definition) {
for(var key in definition) {
if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
}
}
};
})();
// webpack/runtime/has_own_property
(() => {
__webpack_require__.o = function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};

})();
// webpack/runtime/make_namespace_object
(() => {
// define __esModule on exports
__webpack_require__.r = function(exports) {
if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
}
Object.defineProperty(exports, '__esModule', { value: true });
};

})();
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
__webpack_require__.r(__webpack_exports__);
/* harmony import */var _style_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./style.css?eccb");

// eslint-disable-next-line no-console
console.log({
css: _style_css__WEBPACK_IMPORTED_MODULE_0__["default"],
aClass: _style_css__WEBPACK_IMPORTED_MODULE_0__["a-class"],
bClass: _style_css__WEBPACK_IMPORTED_MODULE_0__.b__class,
cClass: _style_css__WEBPACK_IMPORTED_MODULE_0__.cClass
});

})();

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import css, {
"a-class" as aClass,
"b__class" as bClass,
cClass,
} from "./style.css";

// eslint-disable-next-line no-console
console.log({ css, aClass, bClass, cClass });
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.a-class {
background: red;
}

.b__class {
color: green;
}

.cClass {
color: blue;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const Self = require("@rspack/core").CssExtractRspackPlugin;

module.exports = {
entry: "./index.js",
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: Self.loader,
},
{
loader: "css-loader",
options: {
esModule: true,
modules: {
namedExport: true,
exportLocalsConvention: "asIs",
},
},
},
],
},
],
},
output: {
module: true,
},
experiments: {
outputModule: true,
},
plugins: [
new Self({
filename: "[name].css",
}),
],
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.Xh041yLR4iCP4RGjge50 {
background: red;
}

.NMuRsxoDwvW8BhSXhFAY {
color: green;
}

.ayWIv09rPsAqE2JznIsI {
color: blue;
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
(() => { // webpackBootstrap
"use strict";
var __webpack_modules__ = ({
"./style.css?eccb": (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
"a-class": function() { return _1; },
b__class: function() { return _2; },
cClass: function() { return _3; }
});
// extracted by css-extract-rspack-plugin
var _1 = "Xh041yLR4iCP4RGjge50";
var _2 = "NMuRsxoDwvW8BhSXhFAY";
var _3 = "ayWIv09rPsAqE2JznIsI";

}),

});
/************************************************************************/
// The module cache
var __webpack_module_cache__ = {};

// The require function
function __webpack_require__(moduleId) {

// Check if module is in cache
var cachedModule = __webpack_module_cache__[moduleId];
if (cachedModule !== undefined) {
return cachedModule.exports;
}
// Create a new module (and put it into the cache)
var module = (__webpack_module_cache__[moduleId] = {
exports: {}
});
// Execute the module function
__webpack_modules__[moduleId](module, module.exports, __webpack_require__);

// Return the exports of the module
return module.exports;

}

/************************************************************************/
// webpack/runtime/define_property_getters
(() => {
__webpack_require__.d = function(exports, definition) {
for(var key in definition) {
if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
}
}
};
})();
// webpack/runtime/has_own_property
(() => {
__webpack_require__.o = function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};

})();
// webpack/runtime/make_namespace_object
(() => {
// define __esModule on exports
__webpack_require__.r = function(exports) {
if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
}
Object.defineProperty(exports, '__esModule', { value: true });
};

})();
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
__webpack_require__.r(__webpack_exports__);
/* harmony import */var _style_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./style.css?eccb");

// eslint-disable-next-line no-console
console.log({
css: _style_css__WEBPACK_IMPORTED_MODULE_0__["default"],
aClass: _style_css__WEBPACK_IMPORTED_MODULE_0__["a-class"],
bClass: _style_css__WEBPACK_IMPORTED_MODULE_0__.b__class,
cClass: _style_css__WEBPACK_IMPORTED_MODULE_0__.cClass
});

})();

})()
;
8 changes: 8 additions & 0 deletions plugin-test/css-extract/cases/es-named-export-as-is/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import css, {
"a-class" as aClass,
"b__class" as bClass,
cClass,
} from "./style.css";

// eslint-disable-next-line no-console
console.log({ css, aClass, bClass, cClass });
11 changes: 11 additions & 0 deletions plugin-test/css-extract/cases/es-named-export-as-is/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.a-class {
background: red;
}

.b__class {
color: green;
}

.cClass {
color: blue;
}
Loading
Loading