Created
August 6, 2020 10:08
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here for JavaScript version