0.18.0 • Published 7 days ago

ember-scoped-css v0.18.0

Weekly downloads
-
License
MIT
Repository
-
Last release
7 days ago

ember-scoped-css

ember-scoped-css is a modern addon that allows you to isolate your CSS in a modular way with co-located scoped CSS. This is a build-time-only addon and therefore is fully supported if your app is built with Embroider.

With ember-scoped-css you can write your component styles in a co-located .css file next to your .hbs or .gjs/.gts files. Every selector you write in your styles is automatically scoped to the component. So you can develop your component with styles isolated from the rest of the application and you don't have to worry about CSS selectors collisions or issues with the CSS cascade.

If you want to read more specifics on how this addon achieves isolation with CSS you can read more in the detailed CSS isolation documentation

As selectors are scoped/renamed during the build process. So there is no performance hit when running the app.

The philosophy of ember-scoped-css is to stick as close to CSS and HTML as possible and not introduce new syntax or concepts unless it is absolutely necessary.

You may also find the docs on CSS @layer interesting. This build tool emits CSS in a @layer.

Compatibility

  • V2 addons
  • non-embroider apps
  • embroider apps

Installation for a non-embroider ember app

npm install --save-dev ember-scoped-css ember-scoped-css-compat

Configuration

In your ember-cli-build.js, you can configure the behavior of scoped-css transformations within the app via

const app = new EmberApp(defaults, { 
  /* ... */ 
  'ember-scoped-css': {
    layerName: 'app-styles', // default: 'components', set to false to disable the layer
    additionalRoots: ['routes/'], // default: [], set this to use scoped-css in pods-using apps
  }
});

Note that supporting pods is opt in, because all apps can have their pods root directory configured differently.

Installation for an embroider app

npm install --save-dev ember-scoped-css

Setup webpack:

// ember-cli-build.js
module.exports = async function (defaults) {
  const { appJsUnplugin } = await import('ember-scoped-css/build');
  
  const app = new EmberApp(defaults, { /* ... */ });

  const { Webpack } = require('@embroider/webpack');

  return require('@embroider/compat').compatBuild(app, Webpack, {
    /* ... */
    packagerOptions: {
      // css loaders for live reloading css
      webpackConfig: {
        plugins: [appJsUnplugin.webpack({ appDir: __dirname })],
        module: {
          rules: [
            // css loaders for production
            {
              test: /\.css$/,
              use: [
                {
                  loader: require.resolve(
                    'ember-scoped-css/build/app-css-loader'
                  ),
                  options: {
                    layerName: 'the-layer-name', // optional
                  }
                },
              ],
            },
            {
              test: /(\.hbs)|(\.js)$/,
              use: [
                {
                  loader: require.resolve(
                    'ember-scoped-css/build/app-dependency-loader'
                  ),
                },
              ],
              exclude: [/node_modules/, /dist/, /assets/],
            },
          ],
        },
      },
    },
  });
}

Installation for a V2 Addon

npm install --save-dev ember-scoped-css
  1. If you want to use .gjs/gts components, @embroider/addon-dev provides a plugin for you, addon.gjs().

There is a deprecated plugin (superseded by @embroider/addon-dev) that uses ember-template-imports -- to use this follow the instructions from rollup-plugin-glimmer-template-tag addon.

This plugin is not recommended, and is archived.

  1. Add the following to your rollup.config.mjs:
+ import { scopedCssUnplugin } from 'ember-scoped-css/build';

// if you want to have some global styles in your addon then
// put them in the styles folder and change the path to the styles folder
// if there are no global styles then you can remove addon.keepAssets
- addon.keepAssets(['**/*.css']),
+ addon.keepAssets(['**/styles/*.css']),

// add the following to the rollup config
+ scopedCssUnplugin.rollup(),

Note that if you're using rollup-plugin-ts, scopedCssUnpulugin.rollup() must come before typescript(/*...*/)

Configuration

In the rollup config, you may pass options:

scopedCssUnplugin.rollup({ 
  layerName: 'utilities', // default: 'components', set to false to disable the layer
});

Usage

With ember-scoped-css you define styles in .css files that are colocated with your components

{{! src/components/my-component.hbs }}
<div data-test-my-component class='hello-class header'><b>Hello</b>, world!</div>
/* src/components/my-component.css */
.hello-class {
  color: red;
}

/* the :global() pseudo-class is used to define a global class. It mean that header class wont be scoped to that component */
.hello-class:global(.header) {
  font-size: 20px;
}

b {
  color: blue;
}

NOTE: that if you're using pods, css co-located with templates/routes/etc will need to be named styles.css

Passing classes as arguments to a component

There is a scoped-class helper that you can use to pass a class name as an argument to a component. The helper takes a class name and returns a scoped class name. scoped-class helper is replaced at build time so there is no performance hit when running the app.

{{! src/components/my-component.hbs }}
<OtherComponent @internalClass={{scoped-class 'hello-class'}} />
<OtherComponent @internalClass={{(scoped-class 'hello-class')}} />
<OtherComponent
  @internalClass={{concat (scoped-class 'hello-class') ' other-class'}}
/>

In gjs/gts/<template>, the above would look like:

import { scopedClass } from 'ember-scoped-css';

<template>
  <OtherComponent @internalClass={{scopedClass 'hello-class'}} />
  <OtherComponent @internalClass={{(scopedClass 'hello-class')}} />
  <OtherComponent
    @internalClass={{concat (scopedClass 'hello-class') ' other-class'}}
  />
</template>

Testing

As classes are renamed during the build process you can't directly verify if classes are present in your tests. To solve this problem you can use the scopedClass function from the ember-scoped-css/test-support module. The function takes the class names and path to the CSS file where are the classes defined and returns the scoped class names.

The path to the CSS file is always relative to the V2 addon root no matter where the test is located.

import { scopedClass } from 'ember-scoped-css/test-support';

test('MyComponent has hello-class', async function (assert) {
  assert.expect(1);

  await render(hbs`
    <MyComponent />
  `);

  const rewrittenClass = scopedClass(
    'hello-class',
    '<module-name>/components/my-component'
  );

  assert.dom('[data-test-my-component]').hasClass(rewrittenClass);
});

Linting

ember-scoped-css exports a ember-template-lint plugin with one rule scoped-class-helper. This lint rule is intended to help you prevent improper use of the scoped-class helper which might not be immediately obvious during regular development. You can read more information in the lint rules documentation

Steps for adding the rule to the project

  1. Add ember-scoped-css plugin to .template-lintrc.js
'use strict';

module.exports = {
	plugins: [
+    'ember-scoped-css/src/template-lint/plugin'
  ],
  1. Add scoped-class-helper rule to .template-lintrc.js
'use strict';

module.exports = {
	plugins: [
    'ember-scoped-css/src/template-lint/plugin'
  ],
  rules: {
+    'scoped-class-helper': 'error',
  }

License

This project is licensed under the MIT License.

0.18.0

7 days ago

0.17.4

26 days ago

0.17.2

1 month ago

0.17.3

1 month ago

0.17.1

2 months ago

0.17.0

2 months ago

0.16.0

2 months ago

0.15.0

5 months ago

0.12.0

8 months ago

0.13.0

7 months ago

0.12.1

7 months ago

0.14.0

7 months ago

0.11.2

11 months ago

0.11.0

11 months ago

0.10.1

11 months ago

0.11.1

11 months ago

0.10.0

11 months ago

0.9.0

11 months ago

0.8.0

11 months ago

0.7.0

12 months ago

0.6.0

12 months ago

0.2.12

1 year ago

0.2.11

1 year ago

0.2.10

1 year ago

0.3.0

1 year ago

0.2.7

1 year ago

0.2.6

1 year ago

0.2.9

1 year ago

0.2.8

1 year ago

0.5.0

12 months ago

0.4.1

12 months ago

0.4.0

1 year ago

0.2.5

1 year ago

0.1.0

1 year ago

0.0.1

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.1.1

1 year ago

0.2.3

1 year ago

0.2.2

1 year ago

0.2.4

1 year ago

0.0.0

1 year ago