| 1 |
 |
| 2 |
 |
| 3 |
|
| 4 |
[![Build Status][travis-image]][travis-url] |
| 5 |
|
| 6 |
A plugin for [esbuild](https://esbuild.github.io/) to handle Sass & SCSS files. |
| 7 |
|
| 8 |
### Features |
| 9 |
* **PostCSS** & **CSS modules** |
| 10 |
* support for **constructable stylesheet** to be used in custom elements or `dynamic style` to be added to the html page |
| 11 |
* Support for **[Sass Embedded](https://github.com/sass/sass/issues/3296) Async API**. (thanks to @NathanBeddoeWebDev) |
| 12 |
* caching |
| 13 |
* **url rewriting** |
| 14 |
* pre-compiling (to add **global resources** to the sass files) |
| 15 |
|
| 16 |
### Breaking Changes (...maybe) |
| 17 |
* It turned out that sass-embedded is not available on every platform (this sucks!) so, in order to improve the compatibility of the |
| 18 |
plugin I had to make it a peer dependency. Once installed, it can be used by setting the new option `embedded` to `true` |
| 19 |
|
| 20 |
### Install |
| 21 |
|
| 22 |
```console |
| 23 |
$ npm i esbuild-sass-plugin |
| 24 |
``` |
| 25 |
|
| 26 |
### Usage |
| 27 |
|
| 28 |
Just add it to your esbuild plugins: |
| 29 |
|
| 30 |
```javascript |
| 31 |
import {sassPlugin} from 'esbuild-sass-plugin' |
| 32 |
|
| 33 |
await esbuild.build({ |
| 34 |
... |
| 35 |
plugins: [sassPlugin()] |
| 36 |
}) |
| 37 |
``` |
| 38 |
|
| 39 |
### Options |
| 40 |
|
| 41 |
You can pass a series of **options** to the plugin that are a superset of Sass |
| 42 |
[compile string options](https://sass-lang.com/documentation/js-api/interfaces/stringoptions/). \ |
| 43 |
The following are the options specific to the plugin with their defaults whether provided: |
| 44 |
|
| 45 |
| Option | Type | Default | |
| 46 |
|---------------------|---------------------------------------------------------------------------------------------------|------------------------------------------| |
| 47 |
| filter | regular expression (in Go syntax) | <code>/\.(s[ac]ss|css)$/</code> | |
| 48 |
| type | `"css"`<br/>`"style"`<br/>`"lit-css"`<br/>`"css-text"` <br/> `(css:string,nonce?:string)=>string` | `"css"` | |
| 49 |
| cache | boolean or Map | `true` (there is one Map per namespace) | |
| 50 |
| transform | function | | |
| 51 |
| loadPaths | [string[]](https://sass-lang.com/documentation/js-api/interfaces/Options#loadPaths) | [] | |
| 52 |
| precompile | function | | |
| 53 |
| importMapper | function | | |
| 54 |
| cssImports | boolean | false | |
| 55 |
| nonce | string | | |
| 56 |
| prefer | string | preferred package.json field | |
| 57 |
| quietDeps | boolean | false | |
| 58 |
| silenceDeprecations | [string[]](https://sass-lang.com/documentation/js-api/interfaces/deprecations/) | [] | |
| 59 |
| embedded | boolean | false | |
| 60 |
Two main options control the plugin: `filter` which has the same meaning of filter in [esbuild](https://esbuild.github.io/plugins/#on-load) |
| 61 |
allowing to select the URLs handled by a plugin instance and then `type` that's what specifies how the css should be rendered and imported. |
| 62 |
|
| 63 |
### `filter` |
| 64 |
The default filter is quite simple but also quite permissive. When specifying a custom regex bear in mind that this |
| 65 |
is in [Go syntax](https://pkg.go.dev/regexp/syntax) |
| 66 |
|
| 67 |
> If you have URLs in your imports and you want the plugin to ignore them you can't just a filter expression like: |
| 68 |
`/^(?!https?:).*\.(s[ac]ss|css)$/` because *Go regex engine doesn't support lookarounds* but you can use |
| 69 |
> **esbuild**'s `external` option to ignore these imports or try a [solution like this one](https://esbuild.github.io/plugins/#on-resolve). |
| 70 |
|
| 71 |
You can try to list multiple plugin instances in order so that the most specific RegEx come first: |
| 72 |
|
| 73 |
```javascript |
| 74 |
await esbuild.build({ |
| 75 |
... |
| 76 |
plugins |
| 77 |
: |
| 78 |
[ |
| 79 |
sassPlugin({ |
| 80 |
filter: /\.module\.scss$/, |
| 81 |
transformWithESBuild: postcssModules() |
| 82 |
}), |
| 83 |
sassPlugin({ |
| 84 |
filter: /\.scss$/ |
| 85 |
}), |
| 86 |
], |
| 87 |
... |
| 88 |
}) |
| 89 |
``` |
| 90 |
|
| 91 |
### `embedded` |
| 92 |
|
| 93 |
This option enables the usage of the faster `sass-embedded` and is **false** by default just **for compatibility reason**. |
| 94 |
|
| 95 |
> Make sure that the `sass-embedded` has been installed as a peer dependency |
| 96 |
> or add it manually to your project if your package manager doesn't do that for you |
| 97 |
> then set this option to `true` and enjoy the speed boost! |
| 98 |
|
| 99 |
### `type` |
| 100 |
|
| 101 |
The example in [Usage](#usage) uses the default type `css` and will use esbuild CSS loader so your transpiled Sass |
| 102 |
will be in `index.css` alongside your bundle. |
| 103 |
|
| 104 |
In all other cases `esbuild` won't process the CSS content which instead will be handled by the plugin. |
| 105 |
> if you want `url()` resolution or other processing you have to use `postcss` like in [this example](https://github.com/glromeo/esbuild-sass-plugin/issues/92#issuecomment-1219209442) |
| 106 |
|
| 107 |
**NOTE:** Since version `2.7.0` the `css` type works also with postcss, CSS modules and more in general |
| 108 |
with any transformation function by keeping an internal cache of CSS chunks (virtual CSS files) |
| 109 |
importing them in the module wrapping the contents |
| 110 |
|
| 111 |
#### `type: "local-css"` |
| 112 |
This mode uses esbuild's built-in CSS modules support (i.e. the [`local-css` loader](https://esbuild.github.io/content-types/#local-css)). |
| 113 |
Use this for lightweight Sass integration that then leverages esbuild's [built-in CSS processing features](https://esbuild.github.io/content-types/#css): |
| 114 |
|
| 115 |
```javascript |
| 116 |
await esbuild.build({ |
| 117 |
... |
| 118 |
plugins: [ |
| 119 |
sassPlugin({ |
| 120 |
filter: /\.module\.scss$/, |
| 121 |
type: 'local-css' |
| 122 |
}), |
| 123 |
sassPlugin({ |
| 124 |
filter: /\.scss$/ |
| 125 |
type: 'css' |
| 126 |
}), |
| 127 |
], |
| 128 |
... |
| 129 |
}) |
| 130 |
``` |
| 131 |
|
| 132 |
#### `type: "style"` |
| 133 |
In this mode the stylesheet will be in the javascript bundle |
| 134 |
and will be dynamically added to the page when the bundle is loaded. |
| 135 |
|
| 136 |
#### `type: "css-text"` |
| 137 |
You can use this mode if you want to use the resulting css text as a string import |
| 138 |
|
| 139 |
```javascript |
| 140 |
await esbuild.build({ |
| 141 |
... |
| 142 |
plugins: [sassPlugin({ |
| 143 |
type: "css-text", |
| 144 |
... // for the options availanle look at 'SassPluginOptions' in index.ts |
| 145 |
})] |
| 146 |
}) |
| 147 |
``` |
| 148 |
|
| 149 |
...and in your module do something like |
| 150 |
|
| 151 |
```javascript |
| 152 |
import cssText from './styles.scss' |
| 153 |
|
| 154 |
customElements.define('hello-world', class HelloWorld extends HTMLElement { |
| 155 |
constructor() { |
| 156 |
super(); |
| 157 |
this.attachShadow({mode: 'open'}); |
| 158 |
this.sheet = new CSSStyleSheet(); |
| 159 |
this.sheet.replaceSync(cssText); |
| 160 |
this.shadowRoot.adoptedStyleSheets = [this.sheet]; |
| 161 |
} |
| 162 |
} |
| 163 |
``` |
| 164 |
|
| 165 |
#### `type: "lit-css"` |
| 166 |
Or you can import a **lit-element** css result using `type: "lit-css"` |
| 167 |
|
| 168 |
```javascript |
| 169 |
import styles from './styles.scss' |
| 170 |
|
| 171 |
@customElement("hello-world") |
| 172 |
export default class HelloWorld extends LitElement { |
| 173 |
|
| 174 |
static styles = styles |
| 175 |
|
| 176 |
render() { |
| 177 |
... |
| 178 |
} |
| 179 |
} |
| 180 |
``` |
| 181 |
|
| 182 |
#### `type: 'function'` |
| 183 |
|
| 184 |
You can now provide your own module factory as type. It has to be a function that receives 2 parameters |
| 185 |
the css text and the nonce token and returns the source content to be added in place of the import. |
| 186 |
|
| 187 |
Look in `test/fixtures` folder for more usage examples. |
| 188 |
|
| 189 |
### `cache` |
| 190 |
The cache is enabled by default and can be turned off with `cache: false`. |
| 191 |
Each plugin instance creates and maintain its own cache (as a Map) and this cache lives for the duration of the build. |
| 192 |
If you want to pass a Map to preserve the cache amongst subsequent builds bear in mind that sharing the very same cache |
| 193 |
between different instances might work just fine or it might lead to issues if the contents are incompatible. |
| 194 |
> If you are not sure of what to do just keep a separate Map for each plugin instance. |
| 195 |
|
| 196 |
### `cssImports` |
| 197 |
when this is set to `true` the plugin rewrites the node-modules relative URLs starting with the `~` prefix so that |
| 198 |
esbuild can resolve them similarly to what `css-loader` does. |
| 199 |
> Although this practice is [kind of deprecated nowadays](https://webpack.js.org/loaders/sass-loader/#resolving-import-at-rules) |
| 200 |
> some packages out there still use this notation (e.g. `formio`) |
| 201 |
> \ |
| 202 |
> so I added this feature to help in cases [like this one](https://github.com/glromeo/esbuild-sass-plugin/issues/74). |
| 203 |
|
| 204 |
### `nonce` |
| 205 |
in presence of Content-Security-Policy |
| 206 |
[(CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src) |
| 207 |
the `nonce` option allows to specify the nonce attribute for the dynamically generated `<style>` |
| 208 |
|
| 209 |
If the `nonce` string is a field access starting with `window`, `process` or `globalThis` it is left in the code without quotes. |
| 210 |
```javascript |
| 211 |
sassPlugin({ |
| 212 |
type: 'style', |
| 213 |
nonce: 'window.__esbuild_nonce__' |
| 214 |
}) |
| 215 |
``` |
| 216 |
This allows to define it globally or to leave it for a subsequent build to resolve it using [esbuild define](https://esbuild.github.io/api/#define). |
| 217 |
```javascript |
| 218 |
define: {'window.__esbuild_nonce__': '"12345"'} |
| 219 |
``` |
| 220 |
|
| 221 |
### `prefer` |
| 222 |
when this option is specified it allows to import npm packages which have `sass` or `style` fields preferring those to `main`. |
| 223 |
|
| 224 |
> **NOTE**: This is an experimental feature |
| 225 |
> * it replaces the internal use of `require.resolve` with browserify `resolve.sync` |
| 226 |
> * it only applies to import prefixed by `~` |
| 227 |
|
| 228 |
### `importMapper` |
| 229 |
|
| 230 |
A function to customize/re-map the import path, both `import` statements in JavaScript/TypeScript code and `@import` |
| 231 |
in Sass/SCSS are covered. |
| 232 |
You can use this option to re-map import paths like tsconfig's `paths` option. |
| 233 |
|
| 234 |
e.g. given this `tsconfig.json` which maps image files paths |
| 235 |
|
| 236 |
```json |
| 237 |
{ |
| 238 |
"compilerOptions": { |
| 239 |
"baseUrl": ".", |
| 240 |
"paths": { |
| 241 |
"@img/*": [ |
| 242 |
"./assets/images/*" |
| 243 |
] |
| 244 |
} |
| 245 |
} |
| 246 |
} |
| 247 |
``` |
| 248 |
|
| 249 |
now you can resolve these paths with `importMapper` |
| 250 |
|
| 251 |
```javascript |
| 252 |
await esbuild.build({ |
| 253 |
..., |
| 254 |
plugins: [sassPlugin({ |
| 255 |
importMapper: (path) => path.replace(/^@img\//, './assets/images/') |
| 256 |
})] |
| 257 |
}) |
| 258 |
``` |
| 259 |
|
| 260 |
### `precompile` |
| 261 |
|
| 262 |
#### - Rewriting relative `url(...)`s |
| 263 |
If your sass reference resources with relative urls (see [#48](https://github.com/glromeo/esbuild-sass-plugin/issues/48)) |
| 264 |
esbuild will struggle to rewrite those urls because it doesn't have idea of the imports that the Sass compiler |
| 265 |
has gone through. Fortunately the new importer API allows to rewrite those relative URLs in absolute ones which |
| 266 |
then esbuild will be able to handle. |
| 267 |
|
| 268 |
Here is an example of how to do the `url(...)` rewrite ([make sure to handle `\` in *Windows*](https://github.com/glromeo/esbuild-sass-plugin/issues/58)) |
| 269 |
```javascript |
| 270 |
const path = require('path') |
| 271 |
|
| 272 |
await esbuild.build({ |
| 273 |
..., |
| 274 |
plugins: [sassPlugin({ |
| 275 |
precompile(source, pathname) { |
| 276 |
const basedir = path.dirname(pathname) |
| 277 |
return source.replace(/(url\(['"]?)(\.\.?\/)([^'")]+['"]?\))/g, `$1${basedir}/$2$3`) |
| 278 |
} |
| 279 |
})] |
| 280 |
}) |
| 281 |
``` |
| 282 |
|
| 283 |
#### - Globals and other Shims (like sass-loader's additionalData) |
| 284 |
Look for a complete example in the [precompile](https://github.com/glromeo/esbuild-sass-plugin/tree/main/test/fixture/precompile) fixture. |
| 285 |
|
| 286 |
Prepending a variable for a specific `pathname`: |
| 287 |
```javascript |
| 288 |
const context = { color: "blue" } |
| 289 |
|
| 290 |
await esbuild.build({ |
| 291 |
..., |
| 292 |
plugins: [sassPlugin({ |
| 293 |
precompile(source, pathname) { |
| 294 |
const prefix = /\/included\.scss$/.test(pathname) ? ` |
| 295 |
$color: ${context.color}; |
| 296 |
` : env |
| 297 |
return prefix + source |
| 298 |
} |
| 299 |
})] |
| 300 |
}) |
| 301 |
``` |
| 302 |
|
| 303 |
Prepending an `@import` of globals file only for the root file that triggered the compilation (to avoid nested files from importing it again): |
| 304 |
```javascript |
| 305 |
const context = { color: "blue" } |
| 306 |
|
| 307 |
await esbuild.build({ |
| 308 |
..., |
| 309 |
plugins: [sassPlugin({ |
| 310 |
precompile(source, pathname, isRoot) { |
| 311 |
return isRoot ? `@import '/path/to/globals.scss';\n${source}` : source |
| 312 |
} |
| 313 |
})] |
| 314 |
}) |
| 315 |
``` |
| 316 |
|
| 317 |
### `transform` |
| 318 |
|
| 319 |
```typescript |
| 320 |
async (this: SassPluginOptions, css: string, resolveDir?: string) => Promise<string> |
| 321 |
``` |
| 322 |
|
| 323 |
It's a function which will be invoked before passing the css to esbuild or wrapping it in a module.\ |
| 324 |
It can be used to do **PostCSS** processing and/or to create **modules** like in the following examples. |
| 325 |
|
| 326 |
> **NOTE:** Since `v1.5.0` transform can return either a string or an esbuild `LoadResult` object. \ |
| 327 |
> This is what `postcssModules` uses to pass Javascript modules to esbuild bypassing the plugin output altogether. |
| 328 |
|
| 329 |
#### - PostCSS |
| 330 |
|
| 331 |
The simplest use case is to invoke PostCSS like this: |
| 332 |
|
| 333 |
```javascript |
| 334 |
const postcss = require('postcss') |
| 335 |
const autoprefixer = require('autoprefixer') |
| 336 |
const postcssPresetEnv = require('postcss-preset-env') |
| 337 |
|
| 338 |
esbuild.build({ |
| 339 |
..., |
| 340 |
plugins: [ |
| 341 |
sassPlugin({ |
| 342 |
async transformWithESBuild(source, resolveDir) { |
| 343 |
const {css} = await postcss([autoprefixer, postcssPresetEnv({stage: 0})]).process(source) |
| 344 |
return css |
| 345 |
} |
| 346 |
}) |
| 347 |
] |
| 348 |
}) |
| 349 |
|
| 350 |
``` |
| 351 |
|
| 352 |
#### - CSS Modules |
| 353 |
|
| 354 |
A helper function is available to do all the work of calling PostCSS to create a CSS module. The usage is something |
| 355 |
like: |
| 356 |
|
| 357 |
```javascript |
| 358 |
const {sassPlugin, postcssModules} = require('esbuild-sass-plugin') |
| 359 |
|
| 360 |
esbuild.build({ |
| 361 |
..., |
| 362 |
plugins: [sassPlugin({ |
| 363 |
transform: postcssModules({ |
| 364 |
// ...put here the options for postcss-modules: https://github.com/madyankin/postcss-modules |
| 365 |
}) |
| 366 |
})] |
| 367 |
}) |
| 368 |
|
| 369 |
``` |
| 370 |
`postcssModules` produces Javascript modules which are handled by esbuild's `js` loader |
| 371 |
|
| 372 |
`postcssModules` also accepts an optional array of plugins for PostCSS as second parameter. |
| 373 |
|
| 374 |
Look into [fixture/css-modules](https://github.com/glromeo/esbuild-sass-plugin/tree/main/test/fixture/css-modules) for |
| 375 |
the complete example. |
| 376 |
|
| 377 |
> **NOTE:** `postcss` and `postcss-modules` have to be added to your `package.json`. |
| 378 |
|
| 379 |
### quietDeps |
| 380 |
|
| 381 |
In order for `quietDeps` to correctly identify external dependencies the `url` option is defaulted to the importing file path URL. |
| 382 |
|
| 383 |
> The `url` option creates problems when importing source SASS files from 3rd party modules in which case the best workaround is to avoid `quietDeps` and [mute the logger](https://sass-lang.com/documentation/js-api/interfaces/stringoptions/#logger) if that's a big issue. |
| 384 |
|
| 385 |
### `silenceDeprecations` |
| 386 |
|
| 387 |
This option accepts an array of properties for deprecations that will omitted from the logs during a build. |
| 388 |
|
| 389 |
### namedExports |
| 390 |
|
| 391 |
This option allows named exports alongside default export when using transform (e.g.PostCSS). |
| 392 |
When this option is `true` "safe-identifiers" is used to sanitize the names |
| 393 |
and make sure they are valid Js identifiers. |
| 394 |
|
| 395 |
Any altered identifier name will be logged in your terminal like: |
| 396 |
|
| 397 |
```bash |
| 398 |
Exported 'class-name' as 'class_name' in 'test/fixtures/named-exports/style.css' |
| 399 |
Exported 'switch' as '_switch' in 'test/fixtures/named-exports/style.css' |
| 400 |
``` |
| 401 |
|
| 402 |
The original name, is still available on `default` export: |
| 403 |
|
| 404 |
```js |
| 405 |
import style, { class_name, _switch } from './style.css' |
| 406 |
console.log(style['class-name'] === class_name) // true |
| 407 |
console.log(style['switch'] === _switch) // true |
| 408 |
``` |
| 409 |
|
| 410 |
Alternatively you can supply a function to control how exported named is generated. |
| 411 |
|
| 412 |
e.g This function implements escaping as it was in the previous version: |
| 413 |
- dashed class names were transformed by replacing all the dashes to `$` sign wrapped underlines, eg. `--` => `$__$` |
| 414 |
- js protected names used as your style class names, were transformed by wrapping the names between `$` signs, eg. `switch` => `$switch$` |
| 415 |
```js |
| 416 |
namedExports: name => { |
| 417 |
return /-/.test(name) && name.replace(/-/g, '_') |
| 418 |
} |
| 419 |
``` |
| 420 |
|
| 421 |
### pnpm |
| 422 |
|
| 423 |
There's a working example of using `pnpm` with `@material` design |
| 424 |
in [issue/38](https://github.com/glromeo/esbuild-sass-plugin/tree/main/test/issues/38) |
| 425 |
|
| 426 |
### Benchmarks |
| 427 |
**Windows 11** Pro - **i7-490K** CPU @ **4.00**GHz - RAM **32**GB - SSD **500**GB |
| 428 |
|
| 429 |
Given 24 × 24 = 576 lit-element files & 576 imported CSS styles plus the import of the full bootstrap 5.1 |
| 430 |
|
| 431 |
| | sass-embedded | sass-embedded (no cache) | dart sass | dart sass (no cache) | |
| 432 |
|------------------------|----------------|--------------------------|-----------|----------------------| |
| 433 |
| **initial build** | 731.312ms | 779.363ms | 2.450s | 2.450s | |
| 434 |
| rebuild (.ts change) | 170.35ms | 188.861ms | 179.125ms | 1.710s | |
| 435 |
| rebuild (.ts change) | 155.802ms | 167.413ms | 176.849ms | 1.576s | |
| 436 |
| rebuild (.scss change) | 203.746ms | 160.601ms | 188.164ms | 1.575s | |
| 437 |
| rebuild (.scss change) | 152.733ms | 144.754ms | 145.835ms | 1.520s | |
| 438 |
|
| 439 |
|
| 440 |
[travis-url]: https://app.travis-ci.com/glromeo/esbuild-sass-plugin |
| 441 |
[travis-image]: https://app.travis-ci.com/glromeo/esbuild-sass-plugin.svg?branch=main |