Giter VIP home page Giter VIP logo

rollup-plugin-scss's Introduction

Rollup multiple .scss, .sass and .css imports

Software License Issues JavaScript Style Guide NPM Latest Version

Installation

npm install --save-dev rollup-plugin-scss sass

If any of them is installed, it will be used automatically, if both installed sass will be used.

Usage

// rollup.config.js
import scss from 'rollup-plugin-scss'

export default {
  input: 'input.js',
  output: {
    file: 'output.js',
    format: 'esm',
    // Removes the hash from the asset filename
    assetFileNames: '[name][extname]'
  },
  plugins: [
    scss() // will output compiled styles to output.css
  ]
}

// OR

export default {
  input: 'input.js',
  output: { file: 'output.js', format: 'esm' },
  plugins: [
    scss({ fileName: 'bundle.css' }) // will output compiled styles to "bundle.css"
  ]
}

// OR

export default {
  input: 'input.js',
  output: { file: 'output.js', format: 'esm' },
  plugins: [
    scss() // will output compiled styles to "assets/output-123hash.css"
  ]
}
// entry.js
import './reset.scss'

Options

Options are passed to the sass compiler (node-sass by default). Refer to the Sass docs for more details on these options.
One notable option is indentedSyntax which you'll need if you're parsing Sass syntax instead of Scss syntax. (e.g. when extracting a Vue <style lang="sass"> tag)
By default the plugin will base the filename for the css on the bundle destination.

scss({
  // Defaults to output.css, Rollup may add a hash to this!
  name: 'output.css',

  // Literal asset filename, bypasses the automated filenaming transformations
  fileName: 'output.css',

  // Callback that will be called ongenerate with two arguments:
  // - styles: the contents of all style tags combined: 'body { color: green }'
  // - styleNodes: an array of style objects: { filename: 'body { ... }' }
  output: function (styles, styleNodes) {
    writeFileSync('bundle.css', styles)
  },

  // Disable any style output or callbacks, import as string
  output: false,

  // Enables/disables generation of source map (default: false)
  sourceMap: true,

  // Choose files to include in processing (default: ['/**/*.css', '/**/*.scss', '/**/*.sass'])
  include: [],

  // Choose files to exclude from processing (default: undefined)
  exclude: [],

  // Determine if node process should be terminated on error (default: false)
  failOnError: true,

  // Prefix global scss. Useful for variables and mixins.
  prefix: `@import "./fonts.scss";`,

  // A Sass (sass compatible) compiler to use
  // - sass and node-sass packages are picked up automatically
  // - you can use this option to specify custom package (e.g. a fork of one of them)
  sass: require('node-sass'),

  // Run postcss processor before output
  processor: () => postcss([autoprefixer({ overrideBrowserslist: 'Edge 18' })]),

  // Process resulting CSS
  processor: (css, map) => ({
    css: css.replace('/*date*/', '/* ' + new Date().toJSON() + ' */'),
    map
  }),

  // or, just string (for backward compatiblity with v2 or simplicity)
  processor: css =>
    css.replace('/*date*/', '/* ' + new Date().toJSON() + ' */'),

  // Log filename and size of generated CSS files (default: true)
  verbose: true

  // Add file/folder to be monitored in watch mode so that changes to these files will trigger rebuilds.
  // Do not choose a directory where rollup output or dest is pointed to as this will cause an infinite loop
  watch: 'src/styles/components',
  watch: ['src/styles/components', 'src/multiple/folders']

  // Any other options are passed to the sass compiler
  includePaths: ...
})

Examples

Using postcss + autoprefixer + includePaths (sass option)

import scss from 'rollup-plugin-scss'
import postcss from 'postcss'
import autoprefixer from 'autoprefixer'

export default {
  input: 'input.js',
  output: {
    file: 'output.js',
    format: 'esm'
  },
  plugins: [
    scss({
      processor: () => postcss([autoprefixer()]),
      includePaths: [
        path.join(__dirname, '../../node_modules/'),
        'node_modules/'
      ]
    })
  ]
}

Minify CSS output:

scss({
  outputStyle: 'compressed'
})

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Contributions and feedback are very welcome. New features should include a test.

To get it running:

  1. Clone the project.
  2. npm install

Credits

License

The MIT License (MIT). Please see License File for more information.

rollup-plugin-scss's People

Contributors

astappiev avatar eagerestwolf avatar git-toni avatar infeligo avatar jackprosser avatar jimschofield avatar lipp avatar mach25 avatar nielsvanvelzen avatar robin-hoodie avatar soulchainer avatar syjsdev avatar thgh avatar tk-o avatar vinayakkulkarni avatar weizhenye avatar zech 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-scss's Issues

Is it possible to input and output multiple files?

I am moving over to rollup from gulp.

I was wondering if it might be possible to get two or more separate input .scss files to output to two or more separate .css files?

file1.scss -> file1.css
file2.scss -> file2.css

Thanks in advance.

sass error `Invalid CSS`

so i have a pretty simple setup, but get an error when using the scss rollup plugin. this compiles fine if i use the sass cli directly. i am new to rollup, and the only help i could find was all webpack related. at first i was thinking i had to specify i am using sass vs scss in the scss plugin config, but i don't see that option.

Error:
	expected ";".
  ╷
4 │   padding: 1em;
  │          ^
  ╵
  stdin 4:10  root stylesheet
import scss from 'rollup-plugin-scss'
import typescript from '@rollup/plugin-typescript'
export default {
  plugins: [
    scss({
      sass: require('sass')
    ),
    typescript()
  ]
}
@import 'systematize/systematize.scss'

body
  padding: 1em
rollup --config rollup.config.js demo/demo.ts --file .dist/demo/demo.js --format umd --name "myBundle"

UPDATE
i noticed in the docs, the default was node-sass, which i updated to just sass, which unblocked the previous problem, but it still seems as though it is looking for scss instead of sass syntax.

Upgrade node-sass

This plugin uses an older version of node-sass which fails to install with Node 9.x.
If you agree, I'll make a PR to upgrade the version of node-sass.

Typescript support

Hello!
Are you planning to provide Typescript's type declarations (e.g. index.d.ts) from npm package contents or via @types/your_package_name?

Improve install time

For some reasons, current node-sass's dependency (^3.10.1) is rebuilt each time it is installed (observed on Mac OS X Sierra with npm 5.0.3 and node 8.0.0).

When installed through other similar plugins (e.g. node-plugin-sass or node-plugin-collect-sass) this does not happen. It seems they are using node-sass 4 instead of 3. Is there any reason why this plugin is stuck on 3? Updating node-sass may be an easy fix to this issue.

High severity vulnerability

  Package         tar                                                  
  Patched in      >=4.4.2                            
  Dependency of   rollup-plugin-scss [dev]     
  Path            rollup-plugin-scss > node-sass > node-gyp > tar
  More info       https://npmjs.com/advisories/803

A solution would be to update in packages.json node-sass version to latest

Unexpected token error w/ Rollup 1.12.0

After upgrading from rollup 1.11.3 to 1.12.0 it looks like rollup no longer parses SCSS files correctly:

> rollup -c build/sass.js

src/sass/index.js → stdout...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
src/sass/normalize.scss (14:5)
12:  */
13:
14: html {

I'm using the typical method of including sass files with JS import:

export default {
    input: 'src/sass/index.js',
    plugins: [
        scss({
            output: 'src/public/css/base.css',
            outputStyle: 'compressed',
            ...
        })
    ],
    output: {
        format: 'cjs'
    }
}

index.js:

import './normalize.scss'
import './base.scss'

...

export default {}

I dug into this a little, but https://github.com/rollup/rollup/releases/tag/v1.12.0 shows as "no breaking changes", so it's no obvious to someone who isn't familiar with rollup's plugin internals.

How to use postcss-url plugin?

I want to use postcss-url plugin. but not work for me. It`s my config,

scss({
      processor: css => postcss([px2rem({ remUnit: 75, remPrecision: 5 }), url({ url: 'copy', assetsPath: './assets' })]),
      output: 'dist/bundle.css',
    }),

Type of node-sass package

Currently, node-sass has been marked as 'optional" dependency in package.json, but there are a few issues:

  • rollup-plugin-scss can't work without node-sass
  • project can't use installation like npm install --no-optional because rollup-plugin-scss will throws issues about missing of node-sass

Also some packages were deprecated

image

Release v3

Some todos that would be nice to check off before releasing v3.

  • Double check if README is clear
  • Add more examples in README (e.g. includePath, processor())
  • Rollup v0 case
  • Typescript type definitions #55
  • Add sourcemaps #66
  • Add test for #66
  • Remove node-sass from dependencies #65
  • Update README to include installation instructions for v3 #65
  • Update README to include installation instructions for v2 #65
  • Add insert option #63
  • Add test for #63
  • Automate testing with Github Actions
  • Add support for yarn PnP #83
  • Update CHANGELOG
  • Update contributors

[Question] How do you make Rollup to watch for changes in sass partials with this?

I have already thrown hours into this and I can't figure it out.
This plugin works great with rollup-watch when you change the main .scss file, which you are importing in your index.js (or whatever your entry point is), but... how you make it to rebundle when you change something in any of your partials?

If you modularize your sass, maybe you don't edit your main.scss file at all. Mine is just a list of @import sentences... So, I import only this file and it calls all the partials. But... it only rebundles if you change the main scss file, so... it renders a bit useless/frustrating.

I guess you're using it and, I hope, you're using partials, so, how you do it?

Any help, please? Thanks :D.


My package.json important part looks like this:

"main": "build/js/bundle.js",
  "scripts": {
    "dev": "rollup -c --watch",
    "reload": "browser-sync start --server 'build' --files 'build'",
    "start": "npm-run-all --parallel reload dev",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

In rollup.config.js my rollup-plugin-css is:

scss({
      outputStyle: 'compressed',
      output: 'build/styles/bundle.css',
    }),

And, of course, in my index.jsx I have:

import '../styles/main.scss';

Generating a JS file that I do not want

The README is not up to date with newer versions of rollup

I have one global.scss file. The plugin creates a global.css file like I expect but it also creates a global file with no extension and just the use strict; javascript on the only line. If I just want to crunch scss —> css why am I getting a js file as well?

Here is the output of rollup:

bundles public/scss/global.scss → public/global...
(!) Generated an empty bundle
public/global.css 995 B
created public/global in 5ms

Here is the rollup.config.js for this section:

{
	input: 'public/scss/global.scss',
	output: {
    file: 'public/global',
    format: 'cjs',
  },
	plugins: [
		scss()
	]
};

This is not the only plugin in the rollup, I am using Svelte as well.

Filtering relative path would fail to transform hoisted dependencies in monorepos.

Consider a project structure like this:

my-project/
- node_modules/
  - some-awesome-style-lib/
    - dist
      - awesome.css
- packages/
  - pkg1/
    - main.js // import 'some-awesome-style-lib/dist/awesome.css'
    - rollup.config.js // uses rollup-plugin-scss
some-awesome-style-lib is under root node_modules because
  • yarn workspace
  • Or hoisted by lerna --hoist
  • Or other fancy reasons

When rolling this kinda configuration, rollup would ask each plugin to transfrom
/path/to/my-project/node_modules/some-awesome-style-lib/

And the rollup-plugin-scss uses the following code to filter the id

const filter = createFilter(options.include || ['**/*.css', '**/*.scss', '**/*.sass'], options.exclude)

createFilter does this under the hood:

micromatch.matcher(path.resolve('**/*.css'))

// which is 

micromatch.matcher('/path/to/my-project/packages/pkg1/**/*.css')

thus awesome.css is refused by rollup-plugin-scss and that causes rollup to throw Unexpected token

I did a small experiment (by modifying the code directly in node_modules) to change **/*.css to /**/*.css and it worked as expected.

I'm wondering can we just change the filters (['**/*.css', '**/*.sass', '**/*.scss']) to absolute ones (['/**/*.css', '/**/*.sass', '/**/*.scss']) ? Would doing so has any potential defects ?

How to export styles alongside of the component.

Hello I am currently having troubles with exporting styles generated to dist folder. That means when i use my library i don't have any styles there.

my dist folder:
vue-packeta-framework.esm.css
vue-packeta-framework.esm.js
vue-packeta-framework.min.js
vue-packeta-framework.ssr.js

rollup.config.js

// rollup.config.js
import fs from 'fs';
import path from 'path';
import vue from 'rollup-plugin-vue';
import alias from '@rollup/plugin-alias';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import babel from '@rollup/plugin-babel';
import PostCSS from 'rollup-plugin-postcss';
import { terser } from 'rollup-plugin-terser';
import minimist from 'minimist';
import scss from 'rollup-plugin-scss'
import css from 'rollup-plugin-css-only'


// Get browserslist config and remove ie from es build targets
const esbrowserslist = fs.readFileSync('./.browserslistrc')
  .toString()
  .split('\n')
  .filter((entry) => entry && entry.substring(0, 2) !== 'ie');

// Extract babel preset-env config, to combine with esbrowserslist
const babelPresetEnvConfig = require('../babel.config')
  .presets.filter((entry) => entry[0] === '@babel/preset-env')[0][1];

const argv = minimist(process.argv.slice(2));

const projectRoot = path.resolve(__dirname, '..');

const baseConfig = {
  input: 'src/entry.js',
  plugins: {
    preVue: [
      alias({
        entries: [
          {
            find: '@',
            replacement: `${path.resolve(projectRoot, 'src')}`,
          },
        ],
      }),
    ],
    replace: {
      preventAssignment: true,
      'process.browser': true,
      'process.env.NODE_ENV': JSON.stringify('production'),
    },
    vue: {

    },
    postVue: [
      resolve({
        extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue'],
      }),

      scss({output: true}),
      // Process only `<style module>` blocks.
      PostCSS({
        modules: {
          generateScopedName: '[local]___[hash:base64:5]',
        },
        include: /&module=.*\.css$/,
      }),
      // Process all `<style>` blocks except `<style module>`.
      PostCSS({ include: /(?<!&module=.*)\.css$/ }),
      commonjs(),
    ],
    babel: {
      exclude: 'node_modules/**',
      extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue'],
      babelHelpers: 'bundled',
    },
  },
};

// ESM/UMD/IIFE shared settings: externals
// Refer to https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
const external = [
  // list external dependencies, exactly the way it is written in the import statement.
  // eg. 'jquery'
  'vue',
];

// UMD/IIFE shared settings: output.globals
// Refer to https://rollupjs.org/guide/en#output-globals for details
const globals = {
  // Provide global variable names to replace your external imports
  // eg. jquery: '$'
  vue: 'Vue',
};

// Customize configs for individual targets
const buildFormats = [];
if (!argv.format || argv.format === 'es') {
  const esConfig = {
    ...baseConfig,
    input: 'src/entry.esm.js',
    external,
    output: {
      file: 'dist/vue-packeta-framework.esm.js',
      format: 'esm',
      exports: 'named',
    },
    plugins: [
      replace(baseConfig.plugins.replace),
      ...baseConfig.plugins.preVue,
      vue(baseConfig.plugins.vue),
      ...baseConfig.plugins.postVue,
      babel({
        ...baseConfig.plugins.babel,
        presets: [
          [
            '@babel/preset-env',
            {
              ...babelPresetEnvConfig,
              targets: esbrowserslist,
            },
          ],
        ],
      }),
    ],
  };
  buildFormats.push(esConfig);
}

if (!argv.format || argv.format === 'cjs') {
  const umdConfig = {
    ...baseConfig,
    external,
    output: {
      compact: true,
      file: 'dist/vue-packeta-framework.ssr.js',
      format: 'cjs',
      name: 'VuePacketaFramework',
      exports: 'auto',
      globals,
    },
    plugins: [
      replace(baseConfig.plugins.replace),
      ...baseConfig.plugins.preVue,
      vue(baseConfig.plugins.vue),
      ...baseConfig.plugins.postVue,
      babel(baseConfig.plugins.babel),
    ],
  };
  buildFormats.push(umdConfig);
}

if (!argv.format || argv.format === 'iife') {
  const unpkgConfig = {
    ...baseConfig,
    external,
    output: {
      compact: true,
      file: 'dist/vue-packeta-framework.min.js',
      format: 'iife',
      name: 'VuePacketaFramework',
      exports: 'auto',
      globals,
    },
    plugins: [
      replace(baseConfig.plugins.replace),
      ...baseConfig.plugins.preVue,
      vue(baseConfig.plugins.vue),
      ...baseConfig.plugins.postVue,
      babel(baseConfig.plugins.babel),
      terser({
        output: {
          ecma: 5,
        },
      }),
    ],
  };
  buildFormats.push(unpkgConfig);
}

// Export config
export default buildFormats;

Can you please help me make it work?

Using postCSS? Are the docs correct?

Is there any additional step to using the postCSS with this plugin? Does someone else need to be installed?

I tried copy-pasting the example code into my rollup config file and I am getting undefined results where my styles are supposed to come out. The whole script works perfectly fine without the postCSS addition, so the issue is most certainly there.

The code I am using in the config file:

 scss({ 
      output: false,
      processor: css => postcss([autoprefixer({ overrideBrowserslist: "Edge 18" })])
    }),

[Question] How to make @import "~bootstrap/scss/bootstrap" work?

In main.js I have import a style.scss file, and in style.scss, I use @import "~bootstrap/scss/bootstrap" like I often do with webpack but rollup doesnot understand ~ sign is node_modules folder
this is my rollup.config.js

import alias from 'rollup-plugin-alias'
import vue from 'rollup-plugin-vue'
import buble from 'rollup-plugin-buble'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import nodeGlobals from 'rollup-plugin-node-globals'
import butternut from 'rollup-plugin-butternut'
import livereload from 'rollup-plugin-livereload'
import serve from 'rollup-plugin-serve'
import scss from 'rollup-plugin-scss'

const plugins = [
  alias({
    vue$: 'vue/dist/vue.common.js'
  }),
  vue({
    autoStyles: false,
    styleToImports: true
  }),
  scss({
    output: 'public/assets/css/app.css',
    includePaths: [
      './node_modules'
    ]
  }),
  buble({
    objectAssign: 'Object.assign'
  }),
  nodeResolve({
    jsnext: true,
    main: true,
    browser: true
  }),
  commonjs(),
  nodeGlobals()
]

const config = {
  input: './src/main.js',
  output: {
    file: './public/assets/js/app.js',
    format: 'es'
  },
  sourcemap: 'inline',
  plugins: plugins
}

const isProduction = process.env.NODE_ENV === `production`
const isDevelopment = process.env.NODE_ENV === `development`

if (isProduction) {
  config.sourceMap = false
  config.plugins.push(butternut())
}

if (isDevelopment) {
  config.plugins.push(livereload())
  config.plugins.push(serve({
    contentBase: './public/',
    port: 8080,
    open: true
  }))
}

export default config

Update readme to show how to use postcss/processors?

Hi there!

I saw back in 0.4.0 the option to hook in a CSS processor was added. Based on the source code, I assumed it would be as simple as this:

scss({
  sass,
  output: false,
  outputStyle: "compressed",
  processor: async (css) => {
    const result = await postcss([autoprefixer]).process(css, { from: undefined })
    return result.css
  },
})

I expected the final result to be my CSS, e.g.:

var styles = 'html{display:flex}'

But instead I get this:

var styles = {}

I checked that all my packages are being loaded correctly and even result.css being returned is an actual string of the CSS I expect, but still I get the above. 🤷

Could it be that this is an async function and that use-case isn't handled? My only guess.

Any insight is appreciated. Thanks!

Missing output

Hi there.

Hopefully I'm just being a dummy - but on using the plugin, I don't seem to get any style output.

Here are the relevant files:

The compiled JS file has no CSS in it:

There is also no bundle output.

What am I missing?

Thanks,
Dave

Getting an "Invalid CSS" error when trying to compile Bootstrap 4.0 plus custom styles

Hello, I'm running into an issue trying to compile custom scss plus Bootstrap 4.0. I'm pretty new to using rollup also, so I'm using create-react-library out of the box to handle the project config. Ultimately, the project will be used for shared internal React UI components.

The error I'm getting is:
Invalid CSS after "v": expected 1 selector or at-rule, was 'var css = "@charset'

Previously, I was using node-sass-chokidar to watch/compile my scss and that worked fine. I think maybe the issue is that I'm trying to reference the css file directly, but the plugin is trying to import it into the head tag using style-inject. Not sure though.

I appreciate any help you can offer. 👍


In my index.scss file I'm importing my stylesheets like so:

@import "variables";
@import "node_modules/bootstrap/scss/bootstrap";
@import "custom-bootstrap";

And here's my rollup.config.js:

import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import scss from 'rollup-plugin-scss'
import url from 'rollup-plugin-url'

import pkg from './package.json'

export default {
  input: 'src/index.js',
  output: [
    {
      file: pkg.main,
      format: 'cjs'
    },
    {
      file: pkg.module,
      format: 'es'
    }
  ],
  plugins: [
    external(),
    postcss({
      modules: true
    }),
    url(),
    babel({
      exclude: 'node_modules/**'
    }),
    resolve(),
    commonjs(),
    scss({
      output: 'dist/css/bundle.css',
      includePaths: ['node_modules']
    })
  ]
}

Then, in package.json I reference the output css like so:

"style": "dist/css/bundle.css",

Move node-sass to optionalDependencies

node-sass requires download binary from Internet, which is usually not provided by proxy service like Artifactory, it needs extra works to make npm i work in enterprise intranet.

If node-sass is moved to optionalDependencies, it can be ignored by npm i --no-optional. And it should not affect normal npm i.

Alias '~' on 'node_modules' not working

May I ask is there any way to reference ~ to node_modules?

I have tried "@rollup/plugin-alias"

alias({
      entries: {
        "~": path.join(__dirname, "node_modules/"),
      },
 })

with includePaths: ["node_modules"], but it seems not working.

The error is this.

Error:
        Can't find stylesheet to import.
  ╷
2 │ @import "~bootstrap/scss/functions";
  │         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
  stdin 2:9  root stylesheet

Thanks for the help.

Compression an injection feature request

Hello, thanks for sharing!

Is there any plan to implement next features:

  1. possibility to compress/minify output css
  2. bundle css together with bundle.js (aka inject feature webpack loaders apply)

I guess there is possibility to do point 1 one by own handler inside output() method, right?

The ongenerate hook used by plugin css is deprecated. The generateBundle hook should be used instead.

Using the latest version of:

npm i -D rollup-plugin-scss@latest (currently 0.4.0)

triggers the plugin error:

The ongenerate hook used by plugin css is deprecated. The generateBundle hook should be used instead.

when i'm using rollup v1+

This is obviously fixed in the repo in the latest commit but not for the npm package

generateBundle (opts) {

Is it possible for you to release the fix to npm as well? Last release was 0.4.0 about a year ago.

Tim

Add possibility to only transform scss to css

👋 Hey, it would be nice to be able to just transform scss to css. It's needed when you have another rollup plugins which expect plain css contents.

plugins: [
  scss(),
  processCss()
]

With current output: false it transforms it to js module with export default. It can be output: 'emit' or smth.

SCSS Module syntax is not parsed

The symptom

When are run rollup -c I get a reasonable build, but I get this error if I use the SCSS double slash comment style:

CssSyntaxError: //../packages/core/src/styles/layout.module.scss:56:8: Unknown word
You tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser

As far as I can tell, I have setup the plugin to use sass and to use CSS Modules. When I try to set the parser to "postcss-scss" I get this other error:

[!] (plugin postcss) TypeError: node.getIterator is not a function

rollup.config.js

import url from "@rollup/plugin-url";
import svgr from "@svgr/rollup";
import autoprefixer from "autoprefixer";
import { resolve } from "path";
import postcssNormalize from "postcss-normalize";
import babel from "rollup-plugin-babel";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";

import packageJson from "./package.json";

export default [
    {
        input: "src/components/index.ts",
        output: [
            {
                file: `${packageJson.main}`,
                format: "cjs",
                sourcemap: true,
            },
            {
                file: `${packageJson.module}`,
                format: "esm",
                sourcemap: true,
            },
        ],
        plugins: [
            // include peer deps in the package
            peerDepsExternal(),
            // The next 2 allow importing commonjs packages like classnames
            commonjs(),
            nodeResolve(),
            // transform
            babel({
                exclude: "node_modules/**",
            }),
            typescript({
                typescript: require("typescript"),
                tsconfig: "./tsconfig-prod.json",
            }),
            postcss({
                plugins: [autoprefixer(), postcssNormalize()],
                // exclude: "src/styles/**/*.scss",
                namedExports: true,
                sourceMap: true,
                extract: false,
                // modules: true,
                autoModules: true,
                minimize: true,
                extensions: [".scss"],
                use: ["sass"],
                // parser: "postcss-scss",
            }),
            url(),
            svgr(),
        ],
    },
};

There are a couple of commented out options, which I have also tried. I'm not sure where to go from here, so any help would be much appreciated.

In the src/components folders I have this folder strcuture pattern for each component:

components ->
                    >  Button ->
                                      > index.ts
                                      > Button.tsx
                                      > Button.module.scss

Keep imports for later loading

I build a component library and I only want to transform SCSS files to CSS files and keep the import statements renamed to the CSS file.
The user of the library is then free to decide which loader he uses and how the CSS is delivered to the browser.
Like @rollup/plugin-typescript does it, it also renames the imports from *.ts to *.js and generates the transpiled files.

Input:

- src
   index.js
   index.scss
import "./index.scss";

Output:

- dist
   index.js
   index.css
// change only the extension.
import "./foo.css";

I made a contrived example using the resolveId hook with the external option:
https://repl.it/@AndyOGo/OldfashionedAnnualCache

The order of imports

Is there a way to control the order of css imports?

In my app.js I have:

import './assets/css/bootstrap.scss';

import layout_a from './layouts/layout-a.vue';  // contains <style> section
import layout_b from './layouts/layout-b.vue';
import page1 from './pages/page1.vue';
import page2 from './pages/page2.vue';

The output bundle css file contains first the <style> sections from all the vue files (in the order they are imported in app.js) and only then it contains bootstrap css. That of course is not good and bootstrap css has to go first so that scoped styles can override bootsrap rules if necessary.

My rollup.config.js looks like:

import vue from 'rollup-plugin-vue2';
import scss from 'rollup-plugin-scss';
// ...

export default {
    input: 'app.js',
    plugins: [
        vue(),
        scss({output: true}),
        // ...
    ],
};

Thanks.

spaces are removed inside calc, if used on property

Hi, I came across a very bizarre thing:

Setup:

scss({ output: false, watch: 'src/styles', })

Below CSS:

opacity: calc(var(--a) - var(--b));

Results in an invalid CSS calc due to the lack of whitespace between the mathematical operation:

    opacity: calc(var(--a)-var(--b));

Weirdly, this does not happen here:

-foo: calc(var(--a) - var(--b));
opacity: var(-foo);

Seems to work ok in sassmeister so I thought it might be specifically related to this package.

support for eyeglass modules?

I'm trying to do a standard eyeglass import right now, and it can't seem to find the module. Do I need to add something in the settings?

weird deprecated and unhandled promise error

when I try to convert a sass file to CSS file the file converted and created but js module don't require or import css file in transpiled js file and it throw error like below:

(node:24744) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
    at A:\Home\neveshafzar\work\Azad\packages\node_modules\rollup-plugin-scss\index.cjs.js:99:20
    at <anonymous>
(node:24744) 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(). (rejection id: 1)
(node:24744) [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.
(node:24744) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
    at A:\Home\neveshafzar\work\Azad\packages\node_modules\rollup-plugin-scss\index.cjs.js:99:20
    at <anonymous>
(node:24744) 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(). (rejection id: 2)
(node:24744) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
    at A:\Home\neveshafzar\work\Azad\packages\node_modules\rollup-plugin-scss\index.cjs.js:99:20
    at <anonymous>
(node:24744) 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(). (rejection id: 3)

import sass from 'rollup-plugin-scss'

Was running into some issues with node-sass, so wanted to switch to rollup-plugin-sass, but I actually made a mistake and did import sass from 'rollup-plugin-scss'; instead, however this worked and fixed my issue, without having to specify the compiler in the options. Only option is output: true.

How did this work? is this intended? Can I keep using the plugin this way?

[Feature Request] Code Splitting

It would be nice to be able to split imports into separate file outputs somehow. I know the focus is on Js and using imports through Js... But if you're going to give the option to output/extract you should also provide the ability to split the output by imported file name. Just a thought, really great plugin though.

@use rules must be written before any other rules.

It would nice to be able to use sass/dartsass and the at-rules, especially the @use since @import has been deprecated(https://sass-lang.com/documentation/at-rules/import). However doing so will most likely yield a compilation error: "@use rules must be written before any other rules."

I looked a bit at the code and it seems like the plugin is concatenating all the scss partials and then compiling it to css. By doing so @use rules will end up in the middle of the concatenated string which yields the error.

I created a small repo to reproduce the issue: https://github.com/jrkarlsson/rollup-plugin-scss-issue

Unable to include css files from installed packages

I'm trying to combine some scss / css files into one bundle using this package. In my entry.js I import all the stylesheets with:

import "awesomplete/awesomplete.css";
import "./simple-modal-custom.css";
import "./custom.scss";

The first one if from an installed module (ie in node_modules/awesomplete/awesomplete.css.
But this files get ignored and only the other 2 get bundled.
If I use relative imports this seems to work:

import "../node_modules/awesomplete/awesomplete.css";

I would expect the first version to work. Am I missing something?

How to minify?

Sorry for the maybe silly question: I'm learning day by day.

How to minify my .scss in the final .css?

Update documentation on usage of indented syntax

I just spent a couple of hours figuring out why I kept getting syntax errors along the lines of:

Error: expected ";".

I figured out pretty quickly that the plugin was parsing this without using the indented syntax, even though my files were being imported as .sass files, not .scss files.

After digging through the Sass Javascript API options I found the indentedSyntax option which was passed through by the plugin.

I think the documentation should:

  1. Make it more clear that you can use the options of the Sass Javascript API
  2. Especially point out the indentedSyntax option

I'm happy to make these changes to the docs as a PR if needed.

Injecting css path through the bundle

Is this possible to automatically import the css sheet while importing the js module?

Actually, I'm finally having to output:

  • a js file
  • a css file

And I wanted to add the css file to the dom through the js one.

Is this something feasible in the current lib state?

Thanks for the job by the way 💪

Sass building error (sass parsed by scss rules)

Plugin is trying to parse sass file using scss rules. How to correct this Behaviour?

Error:
Invalid CSS after "...on keyframes */": expected 1 selector or at-rule, was ".animate-warn"
Solution:
fix your Sass code

Using latest rollup and plugin version.

config:

plugins: [
      copy({
        'src/renderer/index.html': 'dist/renderer/index.html',
        'src/renderer/assets': 'dist/renderer/assets',
      }),
      builtins(),
      resolve(),
      commonjs(),
      vue({
        css: false,
      }),
      scss({
        output: 'dist/renderer/index.css',
      }),
      css(),
      typescript(),
      babel({
        exclude: 'node_modules/**',
      }),
      production &&
        minify({
          comments: false,
        }),
    ],

Sample sass code:

/* Animation keyframes */
.animate-warn
  animation-delay: 1s
  animation-duration: 5s
  animation-fill-mode: both
  animation-iteration-count: infinite
  animation-name: jump
  transform-origin: 50%
  will-change: transform
  -webkit-animation-duration: 5s
  -webkit-animation-fill-mode: both
  -webkit-animation-name: jump

Add documentation regarding "includePath" property

By looking at the doc, I found that is there is no way to use includePath, however by looking into code that is actually possible.

    scss({
      output: true,
      processor: () => postcss([autoprefixer()]),
      includePaths: [path.join(__dirname, '../../node_modules/'), 'node_modules/']
    }),

Please update the documentation to mention all such properties.

[Bug] node-sass incompatible with MDC

Here's the traceback:

src/index.js → dist/bundle.js...
[!] (plugin css) Error: Invalid CSS after "@include mixins": expected 1 selector or at-rule, was ".core-styles;"
Error: Invalid CSS after "@include mixins": expected 1 selector or at-rule, was ".core-styles;"
    at Object.module.exports.renderSync (./node_modules/node-sass/lib/index.js:441:16)
    at compileToCSS (./node_modules/rollup-plugin-scss/index.cjs.js:23:40)
    at Object.generateBundle (./node_modules/rollup-plugin-scss/index.cjs.js:88:17)
    at ./node_modules/rollup/dist/shared/node-entry.js:13113:25
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:94:5)

Here's the rollup.config.js:

import svelte from 'rollup-plugin-svelte'
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import serve from 'rollup-plugin-serve'
import scss from 'rollup-plugin-scss'

export default {
    input: 'src/index.js',
    output: {
        //  sourcemap: true,
        file: 'dist/bundle.js',
        format: 'iife',
        name: 'app'
    },
    plugins: [
        svelte({
            dev: true,
            emitCss: true,
        }),
        resolve(),
        commonjs(),
        scss({
            output: 'dist/bundle.css',
            failOnError: true
        }),
        serve({
            contentBase: 'dist',
            verbose: true,
            host: '0.0.0.0',
            port: 8000,
            headers: {'Access-Control-Allow-Origin': '*'}
        })
    ],
    watch: {
        clearScreen: false
    }
}

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.