Skip to content

Instantly share code, notes, and snippets.

@amoshydra
Created August 6, 2020 10:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amoshydra/4067ef925d335dd49b3b30bd8c26b2af to your computer and use it in GitHub Desktop.
Save amoshydra/4067ef925d335dd49b3b30bd8c26b2af to your computer and use it in GitHub Desktop.
A build module for Nuxt 2 that add support for *.module.css / *.module.scss CSS module files
import type { Module } from '@nuxt/types';
import type * as webpack from 'webpack';
class UnableToExtendError extends Error {
constructor() {
super('Unable to configure for css module');
}
}
const isCssOrScssRule = (rule: webpack.RuleSetRule): boolean | undefined => {
const test = rule.test;
if (!(test instanceof RegExp)) { return; }
return ['.css', '.scss'].some(x => x.match(test));
};
const prepareNewRule = (existingCssModuleRule: webpack.RuleSetRule, parentRule: webpack.RuleSetRule): webpack.RuleSetRule => {
const test = parentRule.test as RegExp;
return {
// Shallow clone rule
...existingCssModuleRule,
// Adjust constrain
resourceQuery: undefined,
test: new RegExp(`\\.module${test.source}`, test.flags),
};
};
const CssModuleExtension: Module = function CssModuleExtension() {
this.extendBuild((config) => {
if (!config.module) { throw new UnableToExtendError(); }
config.module.rules
.filter(isCssOrScssRule)
.forEach((rule) => {
const oneOf = rule.oneOf;
if (!oneOf) { throw new UnableToExtendError(); }
// Find an existing rule that matched resourceQuery 'module'
const index = oneOf.findIndex(({ resourceQuery }) => resourceQuery instanceof RegExp && resourceQuery.test('module'));
const cssModuleRule = oneOf[index];
if (!cssModuleRule) { throw new UnableToExtendError(); }
// Create new rule
const newCssModuleRule = prepareNewRule(cssModuleRule, rule);
// Insert rule after existing css module rule
oneOf.splice(index + 1, 0, newCssModuleRule);
})
;
});
};
export default CssModuleExtension;
@amoshydra
Copy link
Author

amoshydra commented Aug 6, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment