2021-01-15 02:51:45 +01:00
|
|
|
import loaderUtils from 'next/dist/compiled/loader-utils'
|
2019-12-11 11:46:12 +01:00
|
|
|
import path from 'path'
|
2021-01-14 02:59:08 +01:00
|
|
|
import { webpack } from 'next/dist/compiled/webpack/webpack'
|
2019-12-11 11:46:12 +01:00
|
|
|
|
2020-01-22 21:26:51 +01:00
|
|
|
const regexLikeIndexModule = /(?<!pages[\\/])index\.module\.(scss|sass|css)$/
|
|
|
|
|
2019-12-11 11:46:12 +01:00
|
|
|
export function getCssModuleLocalIdent(
|
|
|
|
context: webpack.loader.LoaderContext,
|
|
|
|
_: any,
|
|
|
|
exportName: string,
|
|
|
|
options: object
|
|
|
|
) {
|
2019-12-11 20:21:40 +01:00
|
|
|
const relativePath = path
|
|
|
|
.relative(context.rootContext, context.resourcePath)
|
|
|
|
.replace(/\\+/g, '/')
|
2019-12-11 11:46:12 +01:00
|
|
|
|
|
|
|
// Generate a more meaningful name (parent folder) when the user names the
|
|
|
|
// file `index.module.css`.
|
2020-01-22 21:26:51 +01:00
|
|
|
const fileNameOrFolder = regexLikeIndexModule.test(relativePath)
|
|
|
|
? '[folder]'
|
|
|
|
: '[name]'
|
2019-12-11 11:46:12 +01:00
|
|
|
|
|
|
|
// Generate a hash to make the class name unique.
|
|
|
|
const hash = loaderUtils.getHashDigest(
|
|
|
|
Buffer.from(`filePath:${relativePath}#className:${exportName}`),
|
|
|
|
'md5',
|
|
|
|
'base64',
|
|
|
|
5
|
|
|
|
)
|
|
|
|
|
|
|
|
// Have webpack interpolate the `[folder]` or `[name]` to its real value.
|
2020-04-10 12:32:55 +02:00
|
|
|
return (
|
|
|
|
loaderUtils
|
|
|
|
.interpolateName(
|
|
|
|
context,
|
|
|
|
fileNameOrFolder + '_' + exportName + '__' + hash,
|
|
|
|
options
|
|
|
|
)
|
|
|
|
.replace(
|
|
|
|
// Webpack name interpolation returns `about.module_root__2oFM9` for
|
|
|
|
// `.root {}` inside a file named `about.module.css`. Let's simplify
|
|
|
|
// this.
|
|
|
|
/\.module_/,
|
|
|
|
'_'
|
|
|
|
)
|
2020-04-27 16:35:10 +02:00
|
|
|
// Replace invalid symbols with underscores instead of escaping
|
|
|
|
// https://mathiasbynens.be/notes/css-escapes#identifiers-strings
|
2020-04-10 17:37:24 +02:00
|
|
|
.replace(/[^a-zA-Z0-9-_]/g, '_')
|
2020-04-27 16:35:10 +02:00
|
|
|
// "they cannot start with a digit, two hyphens, or a hyphen followed by a digit [sic]"
|
|
|
|
// https://www.w3.org/TR/CSS21/syndata.html#characters
|
|
|
|
.replace(/^(\d|--|-\d)/, '__$1')
|
2020-04-10 12:32:55 +02:00
|
|
|
)
|
2019-12-11 11:46:12 +01:00
|
|
|
}
|