refactor: server styles

This commit is contained in:
cha0s 2022-03-18 16:58:48 -05:00
parent 958f3b80a1
commit 6a3ab9d81c
3 changed files with 28 additions and 4 deletions

View File

@ -1,4 +1,11 @@
const {join} = require('path');
module.exports = {
babel: {
plugins: [
join(__dirname, '..', 'src', 'server', 'style-loader'),
],
},
stubs: {
server: [
/\.(c|s[ac])ss$/,

View File

@ -24,10 +24,8 @@ export default {
const extract = {};
const style = {};
if ('server' === target) {
extract.enabled = true;
extract.plugin = {
filename: 'index.css',
};
extract.enabled = false;
style.injectType = 'lazyStyleTag';
}
if ('http' === target) {
extract.enabled = isProduction;

View File

@ -0,0 +1,19 @@
const parser = require('@babel/parser');
const types = require('@babel/types');
// On the server we use `lazyStyleTag` to avoid either dying over the lack of `document` or the
// inefficiency of extracting styles needlessly. When importing CSS modules, `lazyStyleTag` moves
// the default export into a named `locals` export. This babel plugin injects a small amount of
// code after the import in order to hide that from client code.
module.exports = () => ({
visitor: {
ImportDeclaration(path) {
if (path.node.source.value.match(/\.module\.(c|s[ac])ss$/)) {
const defaultSpecifier = path.node.specifiers.find(types.isImportDefaultSpecifier);
const {name} = defaultSpecifier.local;
defaultSpecifier.local.name = `${name}__default`;
path.insertAfter(parser.parse(`const ${name} = ${name}__default?.locals || ${name}__default`));
}
},
},
});