Coder Social home page Coder Social logo

anidetrix / rollup-plugin-styles Goto Github PK

View Code? Open in Web Editor NEW
240.0 3.0 42.0 3.54 MB

🎨 Universal Rollup plugin for styles: PostCSS, Sass, Less, Stylus and more.

Home Page: https://anidetrix.github.io/rollup-plugin-styles

License: MIT License

JavaScript 8.80% TypeScript 87.37% CSS 1.57% SCSS 1.51% Less 0.37% Stylus 0.18% Sass 0.07% Shell 0.13%
rollup postcss css scss sass stylus less css-modules rollup-plugin rollup-plugin-styles

rollup-plugin-styles's Introduction

Stats Top Langs

rollup-plugin-styles's People

Contributors

anidetrix avatar dependabot-preview[bot] avatar felipecrs avatar headfox avatar kherock avatar peschee avatar pioug avatar rchl avatar runningcoderlee avatar semantic-release-bot avatar tony avatar zhihuahuang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

rollup-plugin-styles's Issues

Re-exporting components grabs all styles

Hey!

A not too uncommon pattern is to re-export components in a index file for shared things like:

export { default as ProgressIndicator } from './progress-indicator';
export { default as ProductCardSection } from './productsection';

We do this to allow more compact imports like
import { ProgressIndicator, ProductCardSection } from "shared-components";
instead of
import ProgressIndicator from "shared-components/progress-indicator"; and so on.
However when only pieces of this re-exported file is imported, all styles from the all the other exported components seems to be dragged along. Would be nice to avoid processing the style imports from the files not explicitly imported!

PostCSS relative urls for npm installed dependencies not resolving.

I am including @mdi/fonts (installed from npm) like so:

import '@mdi/font/css/materialdesignicons.css';

This file contains the following @font-face declaration

@font-face {
  font-family: "Material Design Icons";
  src: url("../fonts/materialdesignicons-webfont.eot?v=5.3.45");
  src: url("../fonts/materialdesignicons-webfont.eot?#iefix&v=5.3.45") format("embedded-opentype"), url("../fonts/materialdesignicons-webfont.woff2?v=5.3.45") format("woff2"), url("../fonts/materialdesignicons-webfont.woff?v=5.3.45") format("woff"), url("../fonts/materialdesignicons-webfont.ttf?v=5.3.45") format("truetype");
  font-weight: normal;
  font-style: normal;
}

I get the following error when bundling:

Unresolved URL `../fonts/materialdesignicons-webfont.eot?v=5.3.45` in `src: url("../fonts/materialdesignicons-webfont.eot?v=5.3.45")`
Unresolved URL `../fonts/materialdesignicons-webfont.eot?#iefix&v=5.3.45` in `src: url("../fonts/materialdesignicons-webfont.eot?#iefix&v=5.3.45") format("embedded-opentype"), url("../fonts/materialdesignicons-webfont.woff2?v=5.3.45") format("woff2"), url("../fonts/materialdesignicons-webfont.woff?v=5.3.45") format("woff"), url("../fonts/materialdesignicons-webfont.ttf?v=5.3.45") format("truetype")`
Unresolved URL `../fonts/materialdesignicons-webfont.woff2?v=5.3.45` in `src: url("../fonts/materialdesignicons-webfont.eot?#iefix&v=5.3.45") format("embedded-opentype"), url("../fonts/materialdesignicons-webfont.woff2?v=5.3.45") format("woff2"), url("../fonts/materialdesignicons-webfont.woff?v=5.3.45") format("woff"), url("../fonts/materialdesignicons-webfont.ttf?v=5.3.45") format("truetype")`
Unresolved URL `../fonts/materialdesignicons-webfont.woff?v=5.3.45` in `src: url("../fonts/materialdesignicons-webfont.eot?#iefix&v=5.3.45") format("embedded-opentype"), url("../fonts/materialdesignicons-webfont.woff2?v=5.3.45") format("woff2"), url("../fonts/materialdesignicons-webfont.woff?v=5.3.45") format("woff"), url("../fonts/materialdesignicons-webfont.ttf?v=5.3.45") format("truetype")`Unresolved URL `../fonts/materialdesignicons-webfont.ttf?v=5.3.45` in `src: url("../fonts/materialdesignicons-webfont.eot?#iefix&v=5.3.45") format("embedded-opentype"), url("../fonts/materialdesignicons-webfont.woff2?v=5.3.45") format("woff2"), url("../fonts/materialdesignicons-webfont.woff?v=5.3.45") format("woff"), url("../fonts/materialdesignicons-webfont.ttf?v=5.3.45") format("truetype")` 

Now, I do not get an error for other asset files that I include directly from node_modules in my css. Something like src: url('fontsource-roboto/files/roboto-latin-400-normal.woff2') format('woff2') is bundled just fine.

I presume this is occurring because all relative paths are being resolved from '.' and not /node_modules/@mdi/font.

In `preserveModules` mode, the emitted style file will be overwritten and the position is not correct

In preserveModules mode, if there are files with the same name in different folders, the emitted style file will be overwritten。

src/
  |- components/
  |       |- Card/
  |       |   |- styles/
  |       |   |    |- index.scss
  |       |   |- Card.tsx
  |       |   |- index.ts
  |       |- index.ts
  |- styles/
  |    |- public.scss
  |- index.ts
// src/components/Card/Card.tsx
import './styles/index.scss

function Card() {
// ...
}

export default Card
// src/components/Card/index.ts
import Card from './Card'

export default Card
// src/components/index.ts
import '../styles/public.scss'

export { default } from './Card'
// src/index.ts
export * from './components'
// rollup.config.js

export default {
  input: 'src/index.ts',
  preserveModules: true,
  output: [
    {
      dir: 'build/es',
      format: 'es',
      assetFileNames: '[name][extname]',
      chunkFileNames: '[name].js',
      entryFileNames: '[name].js',
      minifyInternalExports: false,
    },
  ],
  plugins: [
    typescript({
      ...
    }),
    styles({
      mode: 'extract',
      url: {
        inline: true,
      },
      sass: {
        impl: 'sass',
        fiber: require('fibers'),
      },
    }),
  ],
}

After bundle:

build/
  |- es/
      |- components/
      |        |-Card/
      |             |- Card.js
      |             |- index.js
      |- index.css
      |- index.js

Expected:

build/
  |- es/
      |- components/
      |        |-Card/
      |             |- Card.css
      |             |- Card.js
      |             |- index.js
      |- index.css
      |- index.js

How to ignore `external` module style files

Thanks for starting this plugin.

Now I have some use cases like this:

index.ts

import 'vexip-ui/dist/vexip-ui.css'
import './style.scss'

// `vexip-ui` is a node module

rollup.config.js

export default [
  {
    external: []
  },
  {
    external: ['vexip-ui']
  }
]

I would like to exclude the style of the module vexip-ui, but all bundles will include the external module style file.

Maybe same to #156 .

hybrid mode (inject + extract)

Is it possible to extract CSS from the main entrypoint but inject CSS for async imports ? Some kind of hybrid mode ;)

import './app.scss' // this CSS will be extracted
await import('./app2.js'); // all css loaded by app2.js will be injected

This could be hooked when using the onExtract when we return false for instance (or maybe we could return "inject")
Another solution would be to transform mode option to accept a callback that would tell wich mode to use depending of the file.

Duplicate emitted files when multiple `url()` references to same file

Some CSS like this:

.thing {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  background-image: url("./img/wire.png"), url("./img/wire.png");
  background-repeat: no-repeat, no-repeat;
  background-position: 33% 0, 66% 0;
  background-size: 11px 56px, 11px 56px;
}

…produces the following Rollup warning:

(!) The emitted file "wire-9d64d534.png" overwrites a previously emitted file of the same name.

While nothing breaks, processing url() assets only once each seems like a good possible improvement.

import 'x.scss' β†’ Unexpected character '@'

I copy bootstrap.scss from node_modules/bootstrap/scss to ./, replace in it each @import "x" with @import "~/bootstrap/scss/x" and then in my .js file I write import './bootstrap.scss'. I have npm-installed sass.

Calling rollup prints:

(node:29622) UnhandledPromiseRejectionWarning: Error: Unexpected character '@' (Note that you need plugins to import files that are not JavaScript)
    at error (file:///git/bapha/node_modules/rollup/dist/es/shared/rollup.js:5150:30)
    at Module.error (file:///git/bapha/node_modules/rollup/dist/es/shared/rollup.js:9631:16)
    at tryParse (file:///git/bapha/node_modules/rollup/dist/es/shared/rollup.js:9545:23)
    at Module.setSource (file:///git/bapha/node_modules/rollup/dist/es/shared/rollup.js:9942:30)
    at ModuleLoader.addModuleSource (file:///git/bapha/node_modules/rollup/dist/es/shared/rollup.js:18074:20)
    at async ModuleLoader.fetchModule (file:///git/bapha/node_modules/rollup/dist/es/shared/rollup.js:18128:9)
    at async Promise.all (index 33)
    at async ModuleLoader.fetchStaticDependencies (file:///git/bapha/node_modules/rollup/dist/es/shared/rollup.js:18152:34)
    at async Promise.all (index 0)
    at async ModuleLoader.fetchModule (file:///git/bapha/node_modules/rollup/dist/es/shared/rollup.js:18129:9)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:29622) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:29622) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

So apparently the line @import "~bootstrap/scss/functions"; is not passed to sass, but is handled by rollup as JavaScript.

My understanding is, that rollup-plugin-styles can be feeded with .scss files and these are converted on the fly to .css.

Relative Asset URL in mode 'inject'

This might be a question due to my lack of understanding or maybe a request for enhancement!

I have a plugin to my main program with injected css, say myPlugin which I dynamically load using the import('./plugins/myPlugins/plugin.js') statement. The plugin contains assets that I am extracting to myPlugin/assets folder and are correctly mapped relative to myPlugin. Now when I load this plugin from main program, it expects the assets in ./assets and not ./plugins/myPlugins/assets. From what I understand this is because css resolve code in the bundle resolves paths relative to src in <script type='module' src='./main.js'> and not relative to the ./plugins/myPlugin./plugin.js.

Is this behaviour by design? Is there a way to modify this behaviour to make css loading relative? (Extracting css does not seem to be sensible here because I have to then have a mechanism to load the css separately, which seems a super weird way of loading a plugin, especially due to the extra burden of tracking multiple entry points per format). Any other suggestions of resolving this conundrum other that literally copying the contents of ./plugins/myPlugin/assets to ./assets?

I'd really appreciate any input (it is literally the last thing I am stuck on for my work)!

postcss issue. not resolving `url` in `src` mixed with `local` attribute

As I mentioned here there is an issue in processing compiled css.
When there is a code with a line like below, postcss does not process it

@font-face {
	font-family: 'PT Sans';
	font-style: normal;
	font-weight: 400;
--->>	src: local('PT Sans'), local('PTSans-Regular'),  url('fonts/PTS-webfont.woff') format('woff');
}

When there is a src attribute mixed with local, then url is not processed at all.
Even url->resolve option does not see it.

Originally posted by @argesoft in #125 (comment)

Allow `autoModules` to be used together with `modules`

Hi there, it looks like when a modules config object is provided, then the regex match using autoModules is ignored:

const supportModules = Boolean(options.modules || autoModules);

For example, using a configuration like the following would result in all stylesheets being treated as modules, rather than just *.module.css:

  styles({
    autoModules: /\.module\.css$/,
    modules: {
        mode: 'local',
        generateScopedName: '[hash]',
    },
  }),

Would you welcome a change to something like the following?

const supportModules = Boolean((!options.autoModules && options.modules) || autoModules)

TypeScript cannot find namespaces sass/less/stylus

With tsc-4.1.3 I get

.../node_modules/.bin/tsc
node_modules/rollup-plugin-styles/dist/index.d.ts:184:62 - error TS2503: Cannot find namespace 'sass'.

184 interface SASSLoaderOptions extends Record<string, unknown>, sass.PublicOptions {
                                                                 ~~~~

.../node_modules/rollup-plugin-styles/dist/index.d.ts:194:62 - error TS2503: Cannot find namespace 'less'.

194 interface LESSLoaderOptions extends Record<string, unknown>, less.PublicOptions {
                                                                 ~~~~

.../node_modules/rollup-plugin-styles/dist/index.d.ts:198:64 - error TS2503: Cannot find namespace 'stylus'.

198 interface StylusLoaderOptions extends Record<string, unknown>, stylus.PublicOptions {
                                                                   ~~~~~~


Found 3 errors.

error Command failed with exit code 2.

I belive this has worked in the past without changing me anything. [email protected]

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Add Support for CSS Module Tree Shaking [feature request]

Feature Request

While CSS is technically considered a side effect, I would like a way to explicitly state that my CSS Modules are not side effects.

Background

I am building a library that stores a bunch of CSS Module files. The library will be consumed by my component library. The advantage of separating the CSS from the components is that I can write component libraries using multiple frameworks (e.g. React, Angular, and Vue) that all use the same exact styles. Since I am guaranteeing that my styles in any given file are locally scoped to only one component, I can guarantee that my CSS files are not side effects.

Currently, the output from this plugin looks something like the following:

var css$some_hash = ".random_hash{background-color:#000000;font-size:24px;color:#ffffff;cursor:pointer}";
var modules_some_hash = {"button":"some_hash"};
styleInject(css$some_hash, {});

export { modules_some_hash as ButtonStyles }

Now, let's assume that I have 10 CSS files that I want to inject using CSS Modules. I essentially get 10 styleInject function calls and 10 named exports. Once I consume the build file, I'll want to do something like the following in my component file:

import React from "react"; // Assuming React just as an example
import { ButtonStyles } from "./index.es.js"; // "index.es.js" is the build file

const Button = ({ title }) => {
    return <button className={ButtonStyles.button}>{title}</button>
}

This works as expected, meaning that the button styles will be injected into the <head> element via styleInject. The problem is that I have 9 other style files that resulted in 9 other styleInject(..) function calls in the build file (i.e. index.es.js). Because these styleInject calls are not wrapped in a function with a /*#__PURE__*/ annotation, just one import will cause all 10 CSS files to be injected into the <head> element. This is not what I want because the other 9 CSS files (other than the one that I import) are not actually being used. This results in a larger build file for my component library, and thus a larger download for consumers of the component library.

Tree Shaking/Dead Code Elimination

Bundlers like Rollup and Webpack understand the /*#__PURE__*/ annotation preceding a function call. Webpack does a good job explaining this (see https://webpack.js.org/guides/tree-shaking/#mark-a-function-call-as-side-effect-free).

The /*#__PURE__*/ annotation tells the bundler "don't call this function unless it is used somewhere else." In the case of this Rollup plugin, we don't want styleInject(..) to be called unless the styles are actually imported somewhere.

Implementation

For reference, here is the current output:

var css = ".random_hash{background-color:#000000;font-size:24px;color:#ffffff;cursor:pointer}";
var modules = {"button":".random_hash"};
styleInject(css, {});

export { modules as ButtonStyles }

If a user of the plugin states "I guarantee that my CSS has no side effects," we want to transform the above code into the following:

var css = ".random_hash{background-color:#000000;font-size:24px;color:#ffffff;cursor:pointer}";
var styleMapping = {"button":".random_hash"};
var modules = /*#__PURE__*/(function() {
  styleInject(css, {});
  return styleMapping;
})();

export { modules as ButtonStyles }

Here is what I changed in the second code snippet:

  1. Wrap the styleInject(..) function call in an IIFE
  2. Use the /*#__PURE__*/ annotation
  3. Instead of exporting var modules = {"button":".random_hash"};, we need to return mapping from the IIFE. Since we are introducing a third variable to the mix, I set the mapping {"button":".random_hash"}; to a variable called styleMapping instead of modules. Now, I can set the result of the IIFE call to the variable modules. Note that modules is still the variable being exported from the file.

We'll also need an option name to tell this plugin to use the /*#__PURE__*/ annotation and IIFE. Some ideas are pure, noSideEffects, and treeShakable (assuming the value would be a boolean).

code splitting example and docs

Hi @Anidetrix and thanks for starting this plugin. You told in ReadMe file that one of the reasons for this plugin is supporting code-splitting:

Complete code splitting support, with respect for multiple entries, preserveModules and manualChunks

Is it supporting now or it's in your roadmap?
If yes I think some examples and docs about this can be useful.

Fix resolution of node_modules for stylus loader

Stylus loader uses the following options to support loading files from node_modules

const basePath = normalizePath(path.dirname(this.id));
const paths = [`${basePath}/node_modules`, basePath];

The problem with this configuration is that it only resolves node_modules correctly if the file sits on the project root. If the file is in <project_root>/src/a/b/c.styl, the extracted dirname will be <project_root>/src/a/b and stylus will be given these paths: <project_root>/src/a/b and <project_root>/src/a/b/node_modules.

failed to locate @import file <imported file>

    at Evaluator.visitImport

The node_modules path was wrong and rollup-plugin-styles should have used <project_root>/node_modules instead. As a quick workaround the following configuration should suffice:

stylesPlugin({
  stylus: {
    paths: [`${process.cwd()}/node_modules`]
  }
}),

I propose to expand tests to cover this case and use this to fix the problem.

 const basePath = normalizePath(path.dirname(this.id)); 
  
 const paths = [`${process.cwd()}/node_modules`, basePath]; 

If you think this is a good idea, I can submit a PR.

EDIT: Add workaround

Import scss files from node_modules

Can't I import scss files from packages inside node modules?

I can import css files like this
@import '~vuetify/dist/vuetify.css';

but when I tried to import scss files like this
@import '~vuetify/src/styles/generic/_colors.scss';
it doesn't work, and give me an error
Can't find stylesheet to import. @import '~vuetify/src/styles/generic/_colors.scss';

Is there any way to import pre compiled style files?

Inject var instead of const?

I have the plugin configured like this:

        styles({
            // https://anidetrix.github.io/rollup-plugin-styles/interfaces/_index_d_.options.html
            mode: ["inject", () => ""], // NOTE: using an empty closure to bypass code-generation in `styles` and just inline the CSS source
            minimize: true,
        }),

(Note that I'm using a custom callback with inject here to bypass the built-in code generation - I just want the CSS as a string, I have my own code for injecting it.)

Now the input:

import css from "./widget.css";

Correctly gets converted to:

const css = "....";

And so far so good.

But then after your plugin, I have the Babel plugin, which is configured to convert const into var.

Somehow that doesn't work?

Other const in my code get converted to var - but the resulting const from this plugin does not.

Changing the order of plugins doesn't seem to change anything.

Is there any way to configure the plugin itself to emit var instead of const?

(Doesn't the plugin order in rollup define the order of processing? or what am I not understanding here?)

Example on how to use (scoped) SCSS plus lit-element

Hi there,

I'm trying to import scss on a lit-element based web component, but I can't seem to make rollup-plugin-styles and rollup-plugin-lit-css to work. On the documentation there's an example for importing pure CSS but how would this work with SCSS?

To be clear:

  • Using the emit mode I'm able to import pure CSS scoped to the WC.
  • Using the default inject mode the compiled CSS is applied globally and therefore is not scoped to the WC.

Is there a way I can import SCSS in a scoped manner?

Thanks in advance

Tree Shakeable Injector

Hey! Love the project, working great for me. However I'd like to be able to tree-shake my styles with my components. For instance, if I had 10 components, all 10 groups of styles would be injected even if only 3 components are used on a page.

I like the approach here where

<div className={style.myThing} />

Becomes

<div className={style().myThing} />

Out of the box that package doesn't work with rollup-plugin-styles. I'm trying to experiment with a custom injector to do it, but no luck just yet.

Is this something you'd consider adding as a built in option?

possible to add attributes to injected style tag?

I need to pass an id attribute to the injected style tag so that I can access the CSS later on. Is it possible to add this functionality? It could be generic and support any number of attribute via some object passed into inject options...

Prevent extraction and injection

Hi there.

I have a use-case where I need to inject my styles into the final JS bundle. Is that possible? I don't see an option to do that from the docs, but maybe I missed it.

Thanks!

{mode: 'extract'} without css modules

https://github.com/Anidetrix/rollup-plugin-styles/blob/master/README.md says:
β€œNote that, by default, generated CSS will be injected into <head>, with CSS also available as default export unless CSS Modules are enabled,”... β€œCSS Modules styles({ modules: true,})”

This means, that CSS Modules are enabled with modules:true and unless the modules are enabled, the css will be injected into head.

It turns out, that style({mode:'extract'}) prevents the automatic injection.

mode:'extract' changes just the file extensionof the entryfilename, but I want to use as name something that contains the hash of the css-content and ideally honours the https://rollupjs.org/guide/en/#outputassetfilenames option.

With style({mode:['extract':'dist/[hash]-e.css']}) the file is called literally [hash]-e.css

With style({mode:['extract':'e.css']}) rollup receives '../e.css' and says the filenames cannot be relative or absolute.

With mode:'emit' I get:
! Error: unexpected token (Note that you need plugins to import files that are not JavaScript)
xxx/zzz.css:
(css code)

β€’ The mode:['extract', 'SECOND-ELEMENT'] shall honour output.dir and be just file without path.
β€’ The generated file shall honour the output.assetFileNames pattern, possibly inserting its own hash in the filename.
β€’ Please elaborate in the documentation how mode:emit is supposed to be used

The hash token in generateScopedName doesn't include the class name in the generated hash

I'm trying to generate classnames similar to webpack's localIdentName where its default is a single hash: https://webpack.js.org/loaders/css-loader/#localidentname

With a single hash token provided to generateScopedName, it looks like it's generated off of the file name and the entire contents of the css file, so every classname within the same document will receive the same hash:

const hash = hasher(`${base}:${css}`);

Would it make sense to use something like hasher(`${base}:${css}:${local}`) here so class names are unique?

less options. provided `paths` do not work.

When I provide paths in the less loader options, loader does not take it into account (or does not receive it).
Other parameters of options work as expected, but paths somehow does not.
When I import file only by its name (as it can be located in different folders depending on config) less loader does not scan provided paths and returns error (plugin styles) Error: Cannot find module './config.less' from '--__dirname--\src\'.

To reproduce:

package.json

{
  "devDependencies": {
    "less": "^3.11.3",
    "rollup": "^2.18.1",
    "rollup-plugin-styles": "^3.10.0"
  }
}

rollup.config.js

const styles = require("rollup-plugin-styles");

module.exports = {
    input: "./src/index.less",
    plugins: [
        styles({
            less: {
                paths: [
                    "./src/config",
                    `${__dirname}/src/config`
                ]
            }
        })
    ]
}

./src/index.less

@import "config.less";

.test {
    color:black;
}

./src/config/config.less

.test {
    color:red;
}

The same scenario works for other less plugins.
Am I doing something wrong?

Tested on windows 10, node v12.18.1

warning about google fonts

Hi @Anidetrix ,
I got this error on my build process:

(!) Plugin styles: Unresolved `@import` in `@import url("https://fonts.googleapis.com/css?family=Gudea:400,700")`

I used google font in some of my scss files. Do I need to set any options to solve this?

CSS code-splitting is broken by Rollup's PR #4104 (Rollup v2.50.2)

This is more of a "heads up" kind of ticket, see all details here : rollup/rollup#4130

I don't know where the fix will be needed, but I suspect in Rollup. You might want to document it anyway.

While I'm here, thanks a lot for this project, it is quite the step forward from "rollup-plugin-postcss". πŸ‘
A fresh release with CSSnano v5 and PostCSS v8 would be great, but you might want to wait and see what Rollup says about the regression above (hence the "heads up").

Add localsConvention option to postcss css modules

It would be great to have localsConvention option, it's useful when you have css file with dashes in classes:

.field-error {
  color: red;
}

Using this option you can import style classes in js this way:

import css from './styles.scss'

console.log(css.fieldError)

// instead of 

console.log(css['field-error'])

Seems like currently there is no way to do this. I've checked source code and it seems postcss-modules package is not used inside so this option can't be passed 😞

SCSS exports support

I'm looking for a way to use SCSS exports in my project.

Currently this works in React like so:

//Colors.scss
$black: #000000;

:export {
  black: $black;
}
//Component.js
import Colors from '../Colors.scss'

console.log(Colors.black)

But I can't seem to get this to work with rollup. Is this something this plugin already supports?

JSON.parse() in MapModifier is feeded with png-file content

When I set plugins:[ style({url: {resolve: console.log}})] my understanding is, that I will see with which parameters url.resolve is called. But apparently it is not called.

In my .css files I have url('..images/x.png'). rollup-plugin-style prints: Unresolved URL in url('..images/x.png') . I find no option how to resolve this, except setting plugins:[ style({url: false})]

With or without it, I get from Unexpected token in MapModifier/JSON.parse. The string that is passed to JSON parse is a png-file-content, so it cannot be parsed but somehow the system finds the file, yetit prints Unresolved url for png files. (it might be differnt pngs that are found and that are sent to JSON.parse())

Inject global scss files before processing styles

thanks for the great plugin!

Is it possible to inject several scss imports to every scss file before processing it?
In our webpack project we use sass-resoucres-loader for that, so we do not need to manually import the helpers in every *.scss file:

{
    loader: 'sass-resources-loader?sourceMap',
    options: {
      resources: [
        resolve(rootDir, 'src/app/styles/utils/rem-to-px.scss'),
        // ...
      ],
    },
  },

src/app/styles/utils/rem-to-px.scss

@function rem($size) {
  $remSize: $size / 16px;
  @return #{$remSize}rem;
}

MyComponent.scss

// note: no explicit import of rem-to-px.scss here
.MyComponent {
  width: rem(24px);
}

is this possible with this or any other rollup plugin right now?
Thanks again!

src in build folder

// rollup.config.js
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
import commonjs from '@rollup/plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'
import styles from 'rollup-plugin-styles'

export default {
  input: ['./src/index.tsx', './src/Icons/index.tsx'],
  output: [
    {
      dir: 'dist',
      format: 'cjs',
      sourcemap: true,
    },
  ],
  external: ['classnames'],
  preserveModules: true,
  plugins: [peerDepsExternal(), commonjs(), typescript(), styles()],
}

dist after build


β”œβ”€β”€ dist
β”‚Β Β  β”œβ”€β”€ _virtual
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ _tslib.js
β”‚Β Β  β”‚Β Β  └── _tslib.js.map
β”œβ”€β”€ node_modules
β”‚Β Β  β”‚Β Β  └── rollup-plugin-styles
β”‚Β Β  └── src
β”‚Β Β      β”œβ”€β”€ Badge
β”‚Β Β      β”œβ”€β”€ ...
β”‚Β Β      β”œβ”€β”€ Icons
β”‚Β Β      β”œβ”€β”€ index.js
β”‚Β Β      └── utils

I expect to get

β”œβ”€β”€ dist
β”‚Β Β  β”œβ”€β”€ Badge
β”‚Β Β  β”œβ”€β”€ ...
β”‚Β Β  β”œβ”€β”€ Icons
β”‚Β Β  β”œβ”€β”€ index.js
β”‚Β Β  └── utils

What should I do?

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Provide an example how to use cssnano with options

Rollup-plugin-styles has the minify option, that calls nanocss. Nanocss has a website describing the different plugins. But I do not get how to pass a particular option to nanocss, e.g. to enable or disable the nomalizeWhitespace plugin.

Custom injector for server-side rendering (loosing treeshakeable ability)

Currently we need to use a custom injector to be able to retrieve all styles for SSR.

import originalInjector from 'rollup-plugin-styles/dist/runtime/inject-css';
const injectCss = (css) => {
    if (typeof document === 'undefined') {
        if (global.ssrStyles) global.ssrStyles.push(css);
        else global.ssrStyles = [];
    }
    originalInjector(css, {
        singleTag: true,
    });
};

export default injectCss;

Then we get the global.ssrStyles on our Next.js _document.tsx

import Document, { Head, Html, Main, NextScript } from 'next/document';

export default class MyDocument extends Document {
    static async getInitialProps(ctx: any) {
        const initialProps = await Document.getInitialProps(ctx);

        //@ts-ignore
        const globalStyle = global.ssrStyles.join(' ');

        return {
            ...initialProps,
            styles: (
                <>
                    {initialProps.styles}
                    {[
                        <style
                            dangerouslySetInnerHTML={{ __html: globalStyle }}
                            id="server-side-styles"
                        />,
                    ]}
                </>
            ),
        };
    }
    render() {
        return (
            <Html lang="fr">
                <Head />
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

My rollup-plugin-styles config (preserveModules enabled):

 styles({
    autoModules: true,
    minimize: true,
    mode: [
        'inject',
        (varname) => {
            const pathInjector = path.resolve('./tools/rollup/inject-css.js');
            return ` import injectCss from '${pathInjector}';injectCss(${varname})`;
        },
    ],
}),

I didn't find a better way to properly inject my css on server-side.
But with this approach we completely loose the ability to use the treeshakeable option.

Do you think that there is a better way to inject our css on server-side render ?

PostCSS Modules composed styles are not included into the bundle

I have following structure on my project:

  • common.module.css // Contains bunch of classes which are to be composed
  • componentA/
    • ComponentA.tsx - imports component-a.module.css
    • component-a.module.css - composes some classes from common
  • componentB/
    • ComponentB.tsx - imports component-b.module.css
    • component-b.module.css - composes some classes from common
  • index.ts - rexport ComponentA and ComponentB

In a resulting bundle I have styles from both components, and it has class names from common, but there is no class definitions from common.
As a workaround, a added import of common.module.css to index and it works.

Still, I think that composes should be treated as import.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

a way to embed already processed files into js file

I'm using vite and im trying to build a single file from my project, but anything I have tried creates an external css file.
I found your plugin for rollup and tried to use it , but it says [plugin:styles] Skipping processed file .... and it doesn't end up in my js file.
I wanted to know if it's possible to force it to embed the css into js file using your plugin ?

Feature Request: Sourcemap Path Transformations

Please provide an option to configure sourcemap path transformations like output.sourcemapPathTransform option that Rollup provides. Alternatively reuse the output.sourcemapPathTransform property if sourcemaps are enabled for css.

SyntaxError with nollup

https://github.com/PepsRyuu/nollup

My configuration looks like this:

    styles({
      mode: ['extract', 'main.css'],
      autoModules: true,
      minimize: process.env.NODE_ENV === 'production'
    }),

When I run nollup, I get multiple errors that look like this:

SyntaxError: Unexpected token (1:0)
    at Object.pp$4.raise (C:\project\node_modules\acorn\dist\acorn.js:2927:15)
    at Object.pp.unexpected (C:\project\node_modules\acorn\dist\acorn.js:698:10)
    at Object.pp$3.parseExprAtom (C:\project\node_modules\acorn\dist\acorn.js:2326:12)
    at Object.parseExprAtom (C:\project\node_modules\nollup\lib\impl\AcornParser.js:10:30)
    at Object.pp$3.parseExprSubscripts (C:\project\node_modules\acorn\dist\acorn.js:2129:21)
    at Object.pp$3.parseMaybeUnary (C:\project\node_modules\acorn\dist\acorn.js:2106:19)
    at Object.pp$3.parseExprOps (C:\project\node_modules\acorn\dist\acorn.js:2041:21)
    at Object.pp$3.parseMaybeConditional (C:\project\node_modules\acorn\dist\acorn.js:2024:21)
    at Object.pp$3.parseMaybeAssign (C:\project\node_modules\acorn\dist\acorn.js:1997:21)
    at Object.pp$3.parseExpression (C:\project\node_modules\acorn\dist\acorn.js:1963:21) {
  pos: 0,
  loc: Position { line: 1, column: 0 },
  raisedAt: 1
}

SyntaxError: Unexpected character '@' (1:0)
    at Object.pp$4.raise (C:\project\node_modules\acorn\dist\acorn.js:2927:15)
    at Object.pp$9.getTokenFromCode (C:\project\node_modules\acorn\dist\acorn.js:4708:10)
    at Object.pp$9.readToken (C:\project\node_modules\acorn\dist\acorn.js:4409:17)
    at Object.pp$9.nextToken (C:\project\node_modules\acorn\dist\acorn.js:4400:17)
    at Object.parse (C:\project\node_modules\acorn\dist\acorn.js:554:10)
    at Function.parse (C:\project\node_modules\acorn\dist\acorn.js:578:37)
    at Object.parse (C:\project\node_modules\nollup\lib\impl\AcornParser.js:48:23)
    at Object.parse (C:\project\node_modules\nollup\lib\impl\PluginContext.js:143:36)
    at Object.transform (C:\project\node_modules\rollup-plugin-styles\dist\index.js:1353:14)
    at _callAsyncHook (C:\project\node_modules\nollup\lib\impl\PluginLifecycle.js:12:31) {
  pos: 0,
  loc: Position { line: 1, column: 0 },
  raisedAt: 0
}

It doesn't seem to break anything though, but it does flood the console.
Looks like it comes from this line: https://github.com/Anidetrix/rollup-plugin-styles/blob/master/src/index.ts#L87
This doesn't happen with rollup-plugin-postcss πŸ‘€

CSS Modules - generateScopedName does not work with globals

While using CSS Modules I think I found a bug. I was migrating from rollup-plugin-postcss where we exported globals AND controlled the scoped naming. I am finding while using this config does not allow you to export globals:

styles({
      autoModules: true,
      extract: false,
      modules: {
        exportGlobals: true,
        generateScopedName: `[name]__[local]___[hash:base64:5]___${getGitCommitHash()}`
      },
      minimize: true,
      use: ['sass']
    }),

If I remove the generateScopedName globals are exported again. Is there a way to control how scoped names are formatted AND export globals?

Unresolved URL error when query string or hash in url

We cannot handle url with query string or hash right now.

For example:

url("../assets/fonts/icons.svg#icons")

Unresolved URL error will be raised because we are trying to resolve the full url instead of the pathname part.

We can walk around this issue by setting a custom resolve func but the query string and hash parts will be removed in the final url.

scss import call does not work with aliases that has special characters

If I create an alias for root folder in the config object and set it to some special character, then the alias does not work in the scss import call but works f.e. in background image.

/* config */
styles({
  ...
  alias: {
    '@': path.join(__dirname),
  }
})

and my folder structure is something like
scss/
images/
foo/

/* foo/style.scss */
@import "@/scss/mixins"; /* does not work */

.foo {
  background: url("@/images/foo.png"); /* for some reason this still works */
}

Everything works if I create separate aliases for scss and images folders, like

styles({
  ...
  alias: {
    'scss': path.join(__dirname, 'scss'),
    'images': path.join(__dirname, 'images'),
  }
})

node_modules folder created in my build folder

Hi @Anidetrix ,
After adding this plugin 2 files created in bellow path, Have you any idea about this?
How I can prevent this?

build/node_modules/rollup-plugin-styles/dist/runtime/inject-css.js
build/node_modules/rollup-plugin-styles/dist/runtime/inject-css.js.map

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch master on the remote Git repository with URL https://x-access-token:[secure]@github.com/Anidetrix/rollup-plugin-styles.git.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

mode extract missing files

So my use case is that I want all of the css to be bundled into a single file. Is this supported?
The closest I have got so far is to use mode: ['extract', 'filename.css']
Even though I have provided the output filename it still respects assetFileNames so I changed this to '[name][extname]'
Luckily I don't have any other assets so this isn't causing an issue.

Whenever I provide a filename for the extract output I loose files. The missing ones tend to be top level imports, code split modules seems to come through OK.

Default mode injection works fine, I just don't want my js bloated with css.
Extract without a filename seems to work OK, just lots of files.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.