Skip to content

Custom CSS Class Names

Nathan Reid edited this page May 18, 2017 · 1 revision

Template Strings

Custom CSS class names can be created by supplying a template string in the package.json:

"cssModules": 
  "cssClassNamingConvention": {
    "template": "some string"
  }
}

The template uses es6 template literal syntax, and has the following fields available (examples use the class .world from the file client/hello.css):

  • scopedName: the default css class name (_client__hello__world)
  • path: the sanitized path to the css file (_client__hello)
  • originalPath: the unsanitized path to the css file (D:\projects\css-modules\demo-css\client\hello.css)
  • name: the class name (world)
  • hasha: a reference to the hasha package
  • shorthash: a reference to the shorthash package

To create hashed CSS classes, you could use one of the following templates (or create your own!):

"template": "${name}--${hasha(scopedName, {algorithm: 'md5'})}" // world--200da8ad03f9a588526a2fe8c1c3fe73
"template": "${name}--${hasha(scopedName, {algorithm: 'md5'}).substring(0, 5)}" // world--200da
"template": "${name}--${shorthash.unique(scopedName)}" // world--1etuHN

Custom template strings will be run through any replacers you have set up.

Custom Generator Functions

If you need more customizaiton, you can create your own custom generator function. Create a new package in your app's packages folder e.g. meteor create --package scoped-name, add it your app, and make it a build plugin by add Plugin. registerBuildPlugin in package.js:

Package.describe({
  name: 'scoped-name',
  version: '0.0.1',
  summary: '',
  git: '',
  documentation: 'README.md'
});

Package.registerBuildPlugin({
  name: 'scoped-name',
  use: [
    'ecmascript',
  ],
  sources: [
    'scoped-name.js'
  ]
});

Then set up your own generator function (scoped-name.js):

global.cssModules = global.cssModules || {};
global.cssModules.generateScopedName = function(exportedName, filePath, sanitisedPath) {
  return `abc-${exportedName}_${sanitisedPath}`;
};

Now your styles will look like abc-world_client__hello.