Full Code of thgh/rollup-plugin-scss for AI

v4 bf6f20399963 cached
35 files
30.6 KB
8.9k tokens
23 symbols
1 requests
Download .txt
Repository: thgh/rollup-plugin-scss
Branch: v4
Commit: bf6f20399963
Files: 35
Total size: 30.6 KB

Directory structure:
gitextract_cyj5qkwz/

├── .github/
│   └── workflows/
│       └── test.yaml
├── .gitignore
├── .prettierignore
├── .vscode/
│   └── settings.json
├── CHANGELOG.md
├── LICENSE
├── README.md
├── index.ts
├── package.json
├── rollup.config.js
├── test/
│   ├── expected.js
│   ├── import-resolution/
│   │   ├── expected.css
│   │   ├── expected.js
│   │   ├── input.js
│   │   ├── input.scss
│   │   ├── main.js
│   │   ├── main.scss
│   │   ├── rollup.config.js
│   │   ├── setup.js
│   │   └── teardown.js
│   ├── input.js
│   ├── input.scss
│   ├── insert/
│   │   ├── expected.js
│   │   └── rollup.config.js
│   ├── node-sass/
│   │   ├── expected.css
│   │   └── rollup.config.js
│   ├── postcss/
│   │   ├── expected.css
│   │   └── rollup.config.js
│   ├── processor/
│   │   ├── expected.css
│   │   └── rollup.config.js
│   ├── sass/
│   │   ├── expected.css
│   │   └── rollup.config.js
│   └── sourcemap/
│       ├── expected.css
│       └── rollup.config.js
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/test.yaml
================================================
name: Node.js CI
on:
  push:
    branches: [v5, v4, v3, v2]
  pull_request:
    branches: [v5, v4, v3, v2]
jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [14.x, 16.x, 18.x]
    steps:
      - uses: actions/checkout@v3
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}
      - run: yarn --frozen-lockfile
      - run: yarn build
      - run: yarn test


================================================
FILE: .gitignore
================================================
# Logs
logs
*.log
npm-debug.log*

# Dependency directory
node_modules

# Unwanted
.idea
.DS_Store

# Build files
index.cjs.js
index.d.ts
index.es.js
/test/**/output.*


================================================
FILE: .prettierignore
================================================
expected.*

================================================
FILE: .vscode/settings.json
================================================
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "workbench.colorCustomizations": {
    "activityBar.background": "#240",
    "activityBarBadge.background": "#690",
    "activityBar.activeBorder": "#690"
  }
}


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to `rollup-plugin-scss` will be documented in this file.

## [Unreleased]

## [3.0.0] - 2021-06-29

### Added

- Add insert option @syJSdev
- Add `sourceMap` option to enable generation of source map @astappiev
- Add Yarn PnP support` @eagerestwolf
- Refactor to Typescript
- Automated testing using Github Actions

### Updated

- Prefer sass over node-sass
- A `processor` can receive map as second parameter and return `{ css: string, map?: string }`
- Remove `node-sass` from optionalDependencies @astappiev <br/>
  **You have to specify `node-sass` or `sass` in your project dependencies alongside `rollup-plugin-scss`**

## [2.6.1] - 2020-10-01

### Updated

- Move node-sass to optionalDependencies @weizhenye

## [2.6.0] - 2020-08-14

### Fixed

- Resolve processor as a promise during transform step @geotrev

### Added

- Add support for postcss processor

## [2.5.0] - 2020-05-07

### Updated

- Fix includePaths before processing @mach25

## [2.4.0] - 2020-04-13

### Added

- Add `sass` option @riri

## [2.2.0] - 2020-04-11

### Added

- Add `watch` option @JimSchofield

## [2.1.0] - 2019-12-22

### Added

- Add `prefix` option @jackprosser

## [2.0.0] - 2019-12-22

### Changed

- Add `node_modules/` in includePaths by default
- Fix cases where output `css` is null or undefined
- Update dependencies

## [1.0.0] - 2019-02-04

### Update

- Update `ongenerate` to `generateBundle`

[unreleased]: https://github.com/thgh/rollup-plugin-scss/compare/v2.2.0...HEAD
[2.2.0]: https://github.com/thgh/rollup-plugin-scss/compare/v2.1.0...v2.2.0
[2.1.0]: https://github.com/thgh/rollup-plugin-scss/compare/v2.0.0...v2.1.0
[2.0.0]: https://github.com/thgh/rollup-plugin-scss/compare/v1.0.0...v2.0.0
[1.0.0]: https://github.com/thgh/rollup-plugin-scss/compare/v0.0.1...v1.0.0
[0.0.1]: https://github.com/thgh/rollup-plugin-scss/releases


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2016 Thomas Ghysels

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
# Rollup multiple .scss, .sass and .css imports

<a href="LICENSE">
  <img src="https://img.shields.io/badge/license-MIT-brightgreen.svg" alt="Software License" />
</a>
<a href="https://github.com/thgh/rollup-plugin-scss/issues">
  <img src="https://img.shields.io/github/issues/thgh/rollup-plugin-scss.svg" alt="Issues" />
</a>
<a href="http://standardjs.com/">
  <img src="https://img.shields.io/badge/code%20style-standard-brightgreen.svg" alt="JavaScript Style Guide" />
</a>
<a href="https://npmjs.org/package/rollup-plugin-scss">
  <img src="https://img.shields.io/npm/v/rollup-plugin-scss.svg?style=flat-squar" alt="NPM" />
</a>
<a href="https://github.com/thgh/rollup-plugin-scss/releases">
  <img src="https://img.shields.io/github/release/thgh/rollup-plugin-scss.svg" alt="Latest Version" />
</a>

## 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

```js
// 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"
  ]
}
```

```js
// entry.js
import './reset.scss'
```

### Options

Options are passed to the sass compiler ([node-sass] by default). Refer to [ the Sass docs](https://sass-lang.com/documentation/js-api#options) for more details on these options. <br/>
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) <br/>
By default the plugin will base the filename for the css on the bundle destination.

```js
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)

```js
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:

```js
scss({
  outputStyle: 'compressed'
})
```

## Changelog

Please see [CHANGELOG](CHANGELOG.md) 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

- [Thomas Ghysels](https://github.com/thgh)
- [All Contributors][link-contributors]

## License

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

[link-author]: https://github.com/thgh
[link-contributors]: ../../contributors
[rollup-plugin-vue]: https://www.npmjs.com/package/rollup-plugin-vue
[rollup-plugin-buble]: https://www.npmjs.com/package/rollup-plugin-buble
[rollup-plugin-babel]: https://www.npmjs.com/package/rollup-plugin-babel
[node-sass]: https://www.npmjs.com/package/node-sass
[sass]: https://www.npmjs.com/package/sass


================================================
FILE: index.ts
================================================
import { dirname } from 'path'
import { createFilter, CreateFilter } from 'rollup-pluginutils'

import type { Plugin } from 'rollup'

export interface CSSPluginOptions {
  exclude?: Parameters<CreateFilter>[1]
  failOnError?: boolean
  /** Literal asset filename, bypasses any hashes in the filename */
  fileName?: string
  include?: Parameters<CreateFilter>[0]
  includePaths?: string[]
  insert?: boolean
  /** Asset name, defaults to output.css, Rollup may add a hash to this! Check out RollupConfig.output.assetFileNames */
  name?: string
  /** @deprecated Use `fileName` instead, currently still available for backwards compatibility */
  output?: string | false | ((css: string, styles: Styles) => void)
  prefix?: string
  processor?: (
    css: string,
    map: string,
    styles: Styles
  ) => CSS | Promise<CSS> | PostCSSProcessor
  sass?: SassRenderer
  sourceMap?: boolean
  verbose?: boolean
  watch?: string | string[]
  outputStyle?: string
}

type ImporterReturnType = { file: string } | { contents: string } | Error | null

type ImporterDoneCallback = (data: ImporterReturnType) => void

type CSS = string | { css: string; map: string }

interface MappedCSS {
  css: string
  map: string
}

interface Styles {
  [id: string]: string
}

interface PostCSSProcessor {
  process: (css: string, options?: any) => MappedCSS
}

interface SassRenderer {
  renderSync: (options: SassOptions) => SassResult
}

interface SassOptions {
  data: string
}

interface SassResult {
  css: Buffer
  map?: Buffer
}

export default function scss(options: CSSPluginOptions = {}): Plugin {
  const filter = createFilter(
    options.include || ['/**/*.css', '/**/*.scss', '/**/*.sass'],
    options.exclude
  )
  const insertStyleFnName = '___$insertStylesToHeader'

  const styles: Styles = {}
  const fileName =
    options.fileName ||
    (options.output === 'string' ? options.output : undefined)
  const name = options.name || 'output.css'
  const prefix = options.prefix ? options.prefix + '\n' : ''
  let includePaths = options.includePaths || ['node_modules/']
  includePaths.push(process.cwd())

  const compileToCSS = async function (scss: string) {
    // Compile SASS to CSS
    if (scss.length) {
      includePaths = includePaths.filter((v, i, a) => a.indexOf(v) === i)
      try {
        const sass = options.sass || loadSassLibrary()

        const render = sass.renderSync(
          Object.assign(
            {
              data: prefix + scss,
              outFile: fileName || name,
              includePaths,
              importer: (
                url: string,
                prev: string,
                done: ImporterDoneCallback
              ): ImporterReturnType | void => {
                /* If a path begins with `.`, then it's a local import and this
                 * importer cannot handle it. This check covers both `.` and
                 * `..`.
                 *
                 * Additionally, if an import path begins with `url` or `http`,
                 * then it's a remote import, this importer also cannot handle
                 * that. */
                if (
                  url.startsWith('.') ||
                  url.startsWith('url') ||
                  url.startsWith('http')
                ) {
                  /* The importer returns `null` to defer processing the import
                   * back to the sass compiler. */
                  return null
                }

                /* If the requested path begins with a `~`, we remove it. This
                 * character is used by webpack-contrib's sass-loader to
                 * indicate the import is from the node_modules folder. Since
                 * this is so standard in the JS world, the importer supports
                 * it, by removing it and ignoring it. */
                const cleanUrl = url.startsWith('~')
                  ? url.replace('~', '')
                  : url

                /* Now, the importer uses `require.resolve()` to attempt
                 * to resolve the path to the requested file. In the case
                 * of a standard node_modules project, this will use Node's
                 * `require.resolve()`. In the case of a Plug 'n Play project,
                 * this will use the `require.resolve()` provided by the
                 * package manager.
                 *
                 * This statement is surrounded by a try/catch block because
                 * if Node or the package manager cannot resolve the requested
                 * file, they will throw an error, so the importer needs to
                 * defer to sass, by returning `null`.
                 *
                 * The paths property tells `require.resolve()` where to begin
                 * resolution (i.e. who is requesting the file). */
                try {
                  let resolved = require.resolve(cleanUrl, {
                    paths: [prefix + scss]
                  })

                  const allowedExtensions: string[] = ['.css', '.scss', '.sass'];

                  const resolvedHasAllowedExtension = allowedExtensions.some((allowedExtension: string) => {
                    return resolved.endsWith(allowedExtension)
                  });

                  /* It is possible that the `resolved` value is unintentionally
                   * a path to an unintended file which shares the same name
                   * but has a different file extension. */
                  if (!resolvedHasAllowedExtension) {
                    for (const [index, allowedExtension] of allowedExtensions.entries()) {
                      try {
                        /* Make an additional attempt to resolve the path by
                         * specifying the file extension. */
                        resolved = require.resolve(cleanUrl + allowedExtension, {
                          paths: [prefix + scss]
                        })

                        /* For the first file extension that allows the path to
                         * be reolved, break out of the loop. */
                        break
                      /* If not the path could not be resolved with the
                       * file extension. */
                      } catch (e) {
                        if (index < allowedExtensions.length - 1) {
                          /* If not the final iteration then proceed
                           *  to the next. */
                          continue
                        } else {
                          /* If the final iteration then re-throw the error
                           *  onto the next catch. */
                          throw e
                        }
                      }
                    }
                  }

                  /* Since `require.resolve()` will throw an error if a file
                   * doesn't exist. It's safe to assume the file exists and
                   * pass it off to the sass compiler. */
                  return { file: resolved }
                } catch (e: any) {
                  /* Just because `require.resolve()` couldn't find the file
                   * doesn't mean it doesn't exist. It may still be a local
                   * import that just doesn't list a relative path, so defer
                   * processing back to sass by returning `null` */
                  return null
                }
              }
            },
            options
          )
        )

        const css = render.css.toString()
        const map = render.map ? render.map.toString() : ''

        // Possibly process CSS (e.g. by PostCSS)
        if (typeof options.processor === 'function') {
          const result = await options.processor(css, map, styles)

          // TODO: figure out how to check for
          // @ts-ignore
          const postcss: PostCSSProcessor = result

          // PostCSS support
          if (typeof postcss.process === 'function') {
            return Promise.resolve(
              postcss.process(css, {
                from: undefined,
                to: fileName || name,
                map: map ? { prev: map, inline: false } : null
              })
            )
          }

          // @ts-ignore
          const output: string | MappedCSS = result

          return stringToCSS(output)
        }
        return { css, map }
      } catch (e: any) {
        if (options.failOnError) {
          throw e
        }
        console.log()
        console.log(red('Error:\n\t' + e.message))
        if (e.message.includes('Invalid CSS')) {
          console.log(green('Solution:\n\t' + 'fix your Sass code'))
          console.log('Line:   ' + e.line)
          console.log('Column: ' + e.column)
        }
        if (e.message.includes('sass') && e.message.includes('find module')) {
          console.log(green('Solution:\n\t' + 'npm install --save-dev sass'))
        }
        if (e.message.includes('node-sass') && e.message.includes('bindings')) {
          console.log(green('Solution:\n\t' + 'npm rebuild node-sass --force'))
        }
        console.log()
      }
    }
    return { css: '', map: '' }
  }

  return {
    name: 'scss',
    intro() {
      return options.insert === true
        ? insertStyleFn.replace(/insertStyleFn/, insertStyleFnName)
        : ''
    },
    async transform(code, id) {
      if (!filter(id)) {
        return
      }

      // Add the include path before doing any processing
      includePaths.push(dirname(id))

      // Rebuild all scss files if anything happens to this folder
      // TODO: check if it's possible to get a list of all dependent scss files
      //       and only watch those
      if (options.watch) {
        const files = Array.isArray(options.watch)
          ? options.watch
          : [options.watch]
        files.forEach(file => this.addWatchFile(file))
      }

      if (options.insert === true) {
        // When the 'insert' is enabled, the stylesheet will be inserted into <head/> tag.
        const { css, map } = await compileToCSS(code)
        return {
          code:
            'export default ' +
            insertStyleFnName +
            '(' +
            JSON.stringify(css) +
            ')',
          map: { mappings: '' }
        }
      } else if (options.output === false) {
        // When output is disabled, the stylesheet is exported as a string
        const { css, map } = await compileToCSS(code)
        return {
          code: 'export default ' + JSON.stringify(css),
          map: { mappings: '' }
        }
      }

      // Map of every stylesheet
      styles[id] = code

      return ''
    },
    async generateBundle(opts) {
      // No stylesheet needed
      if (options.output === false || options.insert === true) {
        return
      }

      // Combine all stylesheets
      let scss = ''
      for (const id in styles) {
        scss += styles[id] || ''
      }

      const compiled = await compileToCSS(scss)

      if (typeof compiled !== 'object' || typeof compiled.css !== 'string') {
        return
      }

      // Emit styles through callback
      if (typeof options.output === 'function') {
        options.output(compiled.css, styles)
        return
      }

      // Don't create unwanted empty stylesheets
      if (!compiled.css.length) {
        return
      }

      // Emit styles to file
      this.emitFile({
        type: 'asset',
        source: compiled.css,
        name,
        fileName
      })

      if (options.sourceMap && compiled.map) {
        let sourcemap = compiled.map
        if (typeof compiled.map.toString === 'function') {
          sourcemap = compiled.map.toString()
        }

        this.emitFile({
          type: 'asset',
          source: sourcemap,
          name: name && name + '.map',
          fileName: fileName && fileName + '.map'
        })
      }
    }
  }
}

/**
 * Create a style tag and append to head tag
 *
 * @param {String} css style
 * @return {String} css style
 */
const insertStyleFn = `function insertStyleFn(css) {
  if (!css) {
    return
  }
  if (typeof window === 'undefined') {
    return
  }

  const style = document.createElement('style');

  style.setAttribute('type', 'text/css');
  style.innerHTML = css;
  document.head.appendChild(style);
  return css
}`

function loadSassLibrary(): SassRenderer {
  try {
    return require('sass')
  } catch (e) {
    return require('node-sass')
  }
}

function stringToCSS(input: string | CSS): MappedCSS {
  if (typeof input === 'string') {
    return { css: input, map: '' }
  }
  return input
}

function red(text: string) {
  return '\x1b[1m\x1b[31m' + text + '\x1b[0m'
}

function green(text: string) {
  return '\x1b[1m\x1b[32m' + text + '\x1b[0m'
}

function getSize(bytes: number) {
  return bytes < 10000
    ? bytes.toFixed(0) + ' B'
    : bytes < 1024000
    ? (bytes / 1024).toPrecision(3) + ' kB'
    : (bytes / 1024 / 1024).toPrecision(4) + ' MB'
}


================================================
FILE: package.json
================================================
{
  "name": "rollup-plugin-scss",
  "version": "4.0.0",
  "description": "Rollup multiple .scss, .sass and .css imports",
  "main": "index.cjs.js",
  "module": "index.es.js",
  "jsnext:main": "index.es.js",
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -cw",
    "lint": "standard rollup.config.js index.es.js",
    "fix": "prettier --write . ",
    "test:node-sass": "cd test/node-sass && rm -f output.* && rollup -c && cmp output.js ../expected.js && cmp output.css expected.css && cd ../..",
    "test:sass": "cd test/sass && rm -f output.* && rollup -c && cmp nested/output.js ../expected.js && cmp nested/output.css expected.css && cd ../..",
    "test:insert": "cd test/insert && rm -f output.* && rollup -c && cmp output.js expected.js && cd ../..",
    "test:postcss": "cd test/postcss && rm -f output.* && rollup -c && cmp output.js ../expected.js && cmp output.css expected.css && cd ../..",
    "test:processor": "cd test/processor && rm -f output.* && rollup -c && cmp output.js ../expected.js && cmp output.css expected.css && cd ../..",
    "test:sourcemap": "cd test/sourcemap && rm -f output.* && rollup -c && cmp output.js ../expected.js && cmp nested/output.css expected.css && cmp nested/output.css.map expected.css.map && cd ../..",
    "test:import-resolution": "cd test/import-resolution && node setup.js && rm -f output.* && rollup -c && node teardown.js && cmp output.js expected.js && cmp output.css expected.css && cd ../..",
    "test": "npm run test:node-sass && npm run test:sass && npm run test:processor && npm run test:postcss && npm run test:sourcemap && npm run test:insert && npm run test:import-resolution",
    "testw": "cd test/node-sass && rm -f output.* && rollup -cw; cd ..",
    "prepare": "rollup -c"
  },
  "keywords": [
    "rollup-plugin",
    "css",
    "sass",
    "scss"
  ],
  "license": "MIT",
  "author": "Thomas Ghysels <info@thomasg.be>",
  "homepage": "https://github.com/thgh/rollup-plugin-scss",
  "bugs": {
    "url": "https://github.com/thgh/rollup-plugin-scss/issues"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/thgh/rollup-plugin-scss"
  },
  "files": [
    "index.cjs.js",
    "index.d.ts",
    "index.es.js"
  ],
  "dependencies": {
    "rollup-pluginutils": "^2.3.3"
  },
  "devDependencies": {
    "@types/node": "^14.14.30",
    "@types/node-sass": "^4.11.1",
    "@types/sass": "^1.16.0",
    "autoprefixer": "^9.8.6",
    "node-sass": "^8",
    "postcss": "^7.0.32",
    "prettier": "2",
    "rollup": "2",
    "rollup-plugin-buble": "0",
    "rollup-plugin-typescript2": "^0.34.0",
    "sass": "^1.26.3",
    "typescript": "^4.1.5"
  },
  "prettier": {
    "arrowParens": "avoid",
    "bracketSpacing": true,
    "insertPragma": false,
    "jsxBracketSameLine": false,
    "printWidth": 80,
    "proseWrap": "preserve",
    "requirePragma": false,
    "semi": false,
    "singleQuote": true,
    "tabWidth": 2,
    "trailingComma": "none",
    "useTabs": false
  }
}


================================================
FILE: rollup.config.js
================================================
import typescript from 'rollup-plugin-typescript2'

export default {
  input: 'index.ts',
  output: [
    {
      exports: 'default',
      file: 'index.es.js',
      format: 'es'
    },
    {
      exports: 'default',
      file: 'index.cjs.js',
      format: 'cjs'
    }
  ],
  plugins: [typescript()],
  external: ['fs', 'path', 'rollup-pluginutils']
}


================================================
FILE: test/expected.js
================================================
console.log('scss imported');


================================================
FILE: test/import-resolution/expected.css
================================================
.importable {
  color: red;
}

.rollup .plugin .scss {
  color: green;
  user-select: none;
}

================================================
FILE: test/import-resolution/expected.js
================================================
console.log('scss imported from native files and node_modules');


================================================
FILE: test/import-resolution/input.js
================================================
import './input.scss'

console.log('scss imported from native files and node_modules')


================================================
FILE: test/import-resolution/input.scss
================================================
@import 'import-resolution-test/main';

.rollup {
  .plugin {
    .scss {
      color: green;
      user-select: none;
    }
  }
}


================================================
FILE: test/import-resolution/main.js
================================================
// A .js file with the same name as the intended .scss file to be imported.


================================================
FILE: test/import-resolution/main.scss
================================================
.importable {
  color: red;
}


================================================
FILE: test/import-resolution/rollup.config.js
================================================
import scss from '../../index.es.js'

export default {
  input: './input.js',
  output: {
    file: 'output.js',
    format: 'esm'
  },
  plugins: [scss({ fileName: 'output.css' })]
}


================================================
FILE: test/import-resolution/setup.js
================================================
const fs = require('node:fs');
const path = require('node:path');

const NODE_MODULES_MOCK_PACKAGE_PATH = path.join(__dirname, '../../node_modules/import-resolution-test');
const CURRENT_DIRECTORY_PATH = path.join(__dirname, '.');

const IMPORTABLE_FILE_NAME = 'main';
const IMPORTABLE_JS_FILE_NAME = `${IMPORTABLE_FILE_NAME}.js`;
const IMPORTABLE_SCSS_FILE_NAME = `${IMPORTABLE_FILE_NAME}.scss`;

/* If one does not already exist,
 * create a path to the node_modules mock package. */
if (!fs.existsSync(NODE_MODULES_MOCK_PACKAGE_PATH)) {
  fs.mkdirSync(NODE_MODULES_MOCK_PACKAGE_PATH);
}

/* Copy the specified file with the .js extension
 * to the node_modules mock package. */
fs.copyFile(
  `${CURRENT_DIRECTORY_PATH}/${IMPORTABLE_JS_FILE_NAME}`,
  `${NODE_MODULES_MOCK_PACKAGE_PATH}/${IMPORTABLE_JS_FILE_NAME}`,
  error => {
    if (error) {
      console.log(error);
    }
  }
)

/* Copy the specified file with the .scss extension
 * to the node_modules mock package. */
fs.copyFile(
  `${CURRENT_DIRECTORY_PATH}/${IMPORTABLE_SCSS_FILE_NAME}`,
  `${NODE_MODULES_MOCK_PACKAGE_PATH}/${IMPORTABLE_SCSS_FILE_NAME}`,
  error => {
    if (error) {
      console.log(error);
    }
  }
)

================================================
FILE: test/import-resolution/teardown.js
================================================
const fs = require('node:fs');
const path = require('node:path');

const NODE_MODULES_MOCK_PACKAGE_PATH = path.join(__dirname, '../../node_modules/import-resolution-test');

/* Now that it has served its purpose,
 * remove the node_modules mock package. */
fs.rm(
  NODE_MODULES_MOCK_PACKAGE_PATH,
  { recursive: true, force: true },
  error => {
    if (error) {
      throw error;
    }
  }
);

================================================
FILE: test/input.js
================================================
import './input.scss'

console.log('scss imported')


================================================
FILE: test/input.scss
================================================
.rollup {
  .plugin {
    .scss {
      color: green;
      user-select: none;
    }
  }
}


================================================
FILE: test/insert/expected.js
================================================
function ___$insertStylesToHeader(css) {
  if (!css) {
    return
  }
  if (typeof window === 'undefined') {
    return
  }

  const style = document.createElement('style');

  style.setAttribute('type', 'text/css');
  style.innerHTML = css;
  document.head.appendChild(style);
  return css
}

___$insertStylesToHeader(".rollup .plugin .scss {\n  color: green;\n  user-select: none;\n}");

console.log('scss imported');


================================================
FILE: test/insert/rollup.config.js
================================================
import scss from '../../index.es.js'

export default {
  input: '../input.js',
  output: {
    file: 'output.js',
    format: 'esm'
  },
  plugins: [scss({ fileName: 'output.css', insert: true })]
}


================================================
FILE: test/node-sass/expected.css
================================================
.rollup .plugin .scss {
  color: green;
  user-select: none; }


================================================
FILE: test/node-sass/rollup.config.js
================================================
import scss from '../../index.es.js'
import sass from 'node-sass'

export default {
  input: '../input.js',
  output: {
    file: 'output.js',
    format: 'esm'
  },
  plugins: [scss({ fileName: 'output.css', sass })]
}


================================================
FILE: test/postcss/expected.css
================================================
.rollup .plugin .scss {
  color: green;
  -ms-user-select: none;
      user-select: none;
}

================================================
FILE: test/postcss/rollup.config.js
================================================
import scss from '../../index.es.js'
import postcss from 'postcss'
import autoprefixer from 'autoprefixer'

export default {
  input: '../input.js',
  output: {
    file: 'output.js',
    format: 'esm'
  },
  plugins: [
    scss({
      fileName: 'output.css',
      processor: () =>
        postcss([autoprefixer({ overrideBrowserslist: 'Edge 18' })])
    })
  ]
}


================================================
FILE: test/processor/expected.css
================================================
.rollup .plugin .scss {
  color: green;
  -ms-user-select: none;
      user-select: none;
}

================================================
FILE: test/processor/rollup.config.js
================================================
import scss from '../../index.es.js'
import postcss from 'postcss'
import autoprefixer from 'autoprefixer'

export default {
  input: '../input.js',
  output: {
    file: 'output.js',
    format: 'esm'
  },
  plugins: [
    scss({
      fileName: 'output.css',
      processor: css => {
        return Promise.resolve(
          postcss([
            autoprefixer({ overrideBrowserslist: 'Edge 18' })
          ]).process(css, { from: undefined })
        )
      }
    })
  ]
}


================================================
FILE: test/sass/expected.css
================================================
.rollup .plugin .scss {
  color: green;
  user-select: none;
}

================================================
FILE: test/sass/rollup.config.js
================================================
import scss from '../../index.es.js'

export default {
  input: '../input.js',
  output: {
    file: 'nested/output.js',
    format: 'esm',
    assetFileNames: '[name][extname]'
  },
  plugins: [scss()]
}


================================================
FILE: test/sourcemap/expected.css
================================================
.rollup .plugin .scss {
  color: green;
  user-select: none;
}

/*# sourceMappingURL=output.css.map */

================================================
FILE: test/sourcemap/rollup.config.js
================================================
import scss from '../../index.es.js'

export default {
  input: '../input.js',
  output: {
    file: 'output.js',
    format: 'esm'
  },
  plugins: [scss({ fileName: 'nested/output.css', sourceMap: true })]
}


================================================
FILE: tsconfig.json
================================================
{
  "display": "Node 12",
  "compilerOptions": {
    "lib": ["es2019", "es2020.promise", "es2020.bigint", "es2020.string"],
    "module": "ESNext",
    "moduleResolution": "node",
    "target": "ES2019",
    "declaration": true,
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}
Download .txt
gitextract_cyj5qkwz/

├── .github/
│   └── workflows/
│       └── test.yaml
├── .gitignore
├── .prettierignore
├── .vscode/
│   └── settings.json
├── CHANGELOG.md
├── LICENSE
├── README.md
├── index.ts
├── package.json
├── rollup.config.js
├── test/
│   ├── expected.js
│   ├── import-resolution/
│   │   ├── expected.css
│   │   ├── expected.js
│   │   ├── input.js
│   │   ├── input.scss
│   │   ├── main.js
│   │   ├── main.scss
│   │   ├── rollup.config.js
│   │   ├── setup.js
│   │   └── teardown.js
│   ├── input.js
│   ├── input.scss
│   ├── insert/
│   │   ├── expected.js
│   │   └── rollup.config.js
│   ├── node-sass/
│   │   ├── expected.css
│   │   └── rollup.config.js
│   ├── postcss/
│   │   ├── expected.css
│   │   └── rollup.config.js
│   ├── processor/
│   │   ├── expected.css
│   │   └── rollup.config.js
│   ├── sass/
│   │   ├── expected.css
│   │   └── rollup.config.js
│   └── sourcemap/
│       ├── expected.css
│       └── rollup.config.js
└── tsconfig.json
Download .txt
SYMBOL INDEX (23 symbols across 4 files)

FILE: index.ts
  type CSSPluginOptions (line 6) | interface CSSPluginOptions {
  type ImporterReturnType (line 31) | type ImporterReturnType = { file: string } | { contents: string } | Erro...
  type ImporterDoneCallback (line 33) | type ImporterDoneCallback = (data: ImporterReturnType) => void
  type CSS (line 35) | type CSS = string | { css: string; map: string }
  type MappedCSS (line 37) | interface MappedCSS {
  type Styles (line 42) | interface Styles {
  type PostCSSProcessor (line 46) | interface PostCSSProcessor {
  type SassRenderer (line 50) | interface SassRenderer {
  type SassOptions (line 54) | interface SassOptions {
  type SassResult (line 58) | interface SassResult {
  function scss (line 63) | function scss(options: CSSPluginOptions = {}): Plugin {
  function loadSassLibrary (line 374) | function loadSassLibrary(): SassRenderer {
  function stringToCSS (line 382) | function stringToCSS(input: string | CSS): MappedCSS {
  function red (line 389) | function red(text: string) {
  function green (line 393) | function green(text: string) {
  function getSize (line 397) | function getSize(bytes: number) {

FILE: test/import-resolution/setup.js
  constant NODE_MODULES_MOCK_PACKAGE_PATH (line 4) | const NODE_MODULES_MOCK_PACKAGE_PATH = path.join(__dirname, '../../node_...
  constant CURRENT_DIRECTORY_PATH (line 5) | const CURRENT_DIRECTORY_PATH = path.join(__dirname, '.');
  constant IMPORTABLE_FILE_NAME (line 7) | const IMPORTABLE_FILE_NAME = 'main';
  constant IMPORTABLE_JS_FILE_NAME (line 8) | const IMPORTABLE_JS_FILE_NAME = `${IMPORTABLE_FILE_NAME}.js`;
  constant IMPORTABLE_SCSS_FILE_NAME (line 9) | const IMPORTABLE_SCSS_FILE_NAME = `${IMPORTABLE_FILE_NAME}.scss`;

FILE: test/import-resolution/teardown.js
  constant NODE_MODULES_MOCK_PACKAGE_PATH (line 4) | const NODE_MODULES_MOCK_PACKAGE_PATH = path.join(__dirname, '../../node_...

FILE: test/insert/expected.js
  function ___$insertStylesToHeader (line 1) | function ___$insertStylesToHeader(css) {
Condensed preview — 35 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (35K chars).
[
  {
    "path": ".github/workflows/test.yaml",
    "chars": 500,
    "preview": "name: Node.js CI\non:\n  push:\n    branches: [v5, v4, v3, v2]\n  pull_request:\n    branches: [v5, v4, v3, v2]\njobs:\n  build"
  },
  {
    "path": ".gitignore",
    "chars": 167,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\n\n# Dependency directory\nnode_modules\n\n# Unwanted\n.idea\n.DS_Store\n\n# Build files\nindex.c"
  },
  {
    "path": ".prettierignore",
    "chars": 10,
    "preview": "expected.*"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 321,
    "preview": "{\n  \"editor.formatOnSave\": true,\n  \"editor.defaultFormatter\": \"esbenp.prettier-vscode\",\n  \"editor.codeActionsOnSave\": {\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 1876,
    "preview": "# Changelog\n\nAll notable changes to `rollup-plugin-scss` will be documented in this file.\n\n## [Unreleased]\n\n## [3.0.0] -"
  },
  {
    "path": "LICENSE",
    "chars": 1081,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2016 Thomas Ghysels\n\nPermission is hereby granted, free of charge, to any person ob"
  },
  {
    "path": "README.md",
    "chars": 5779,
    "preview": "# Rollup multiple .scss, .sass and .css imports\n\n<a href=\"LICENSE\">\n  <img src=\"https://img.shields.io/badge/license-MIT"
  },
  {
    "path": "index.ts",
    "chars": 12943,
    "preview": "import { dirname } from 'path'\nimport { createFilter, CreateFilter } from 'rollup-pluginutils'\n\nimport type { Plugin } f"
  },
  {
    "path": "package.json",
    "chars": 2979,
    "preview": "{\n  \"name\": \"rollup-plugin-scss\",\n  \"version\": \"4.0.0\",\n  \"description\": \"Rollup multiple .scss, .sass and .css imports\""
  },
  {
    "path": "rollup.config.js",
    "chars": 356,
    "preview": "import typescript from 'rollup-plugin-typescript2'\n\nexport default {\n  input: 'index.ts',\n  output: [\n    {\n      export"
  },
  {
    "path": "test/expected.js",
    "chars": 30,
    "preview": "console.log('scss imported');\n"
  },
  {
    "path": "test/import-resolution/expected.css",
    "chars": 93,
    "preview": ".importable {\n  color: red;\n}\n\n.rollup .plugin .scss {\n  color: green;\n  user-select: none;\n}"
  },
  {
    "path": "test/import-resolution/expected.js",
    "chars": 65,
    "preview": "console.log('scss imported from native files and node_modules');\n"
  },
  {
    "path": "test/import-resolution/input.js",
    "chars": 87,
    "preview": "import './input.scss'\n\nconsole.log('scss imported from native files and node_modules')\n"
  },
  {
    "path": "test/import-resolution/input.scss",
    "chars": 131,
    "preview": "@import 'import-resolution-test/main';\n\n.rollup {\n  .plugin {\n    .scss {\n      color: green;\n      user-select: none;\n "
  },
  {
    "path": "test/import-resolution/main.js",
    "chars": 76,
    "preview": "// A .js file with the same name as the intended .scss file to be imported.\n"
  },
  {
    "path": "test/import-resolution/main.scss",
    "chars": 30,
    "preview": ".importable {\n  color: red;\n}\n"
  },
  {
    "path": "test/import-resolution/rollup.config.js",
    "chars": 184,
    "preview": "import scss from '../../index.es.js'\n\nexport default {\n  input: './input.js',\n  output: {\n    file: 'output.js',\n    for"
  },
  {
    "path": "test/import-resolution/setup.js",
    "chars": 1187,
    "preview": "const fs = require('node:fs');\nconst path = require('node:path');\n\nconst NODE_MODULES_MOCK_PACKAGE_PATH = path.join(__di"
  },
  {
    "path": "test/import-resolution/teardown.js",
    "chars": 395,
    "preview": "const fs = require('node:fs');\nconst path = require('node:path');\n\nconst NODE_MODULES_MOCK_PACKAGE_PATH = path.join(__di"
  },
  {
    "path": "test/input.js",
    "chars": 52,
    "preview": "import './input.scss'\n\nconsole.log('scss imported')\n"
  },
  {
    "path": "test/input.scss",
    "chars": 91,
    "preview": ".rollup {\n  .plugin {\n    .scss {\n      color: green;\n      user-select: none;\n    }\n  }\n}\n"
  },
  {
    "path": "test/insert/expected.js",
    "chars": 420,
    "preview": "function ___$insertStylesToHeader(css) {\n  if (!css) {\n    return\n  }\n  if (typeof window === 'undefined') {\n    return\n"
  },
  {
    "path": "test/insert/rollup.config.js",
    "chars": 199,
    "preview": "import scss from '../../index.es.js'\n\nexport default {\n  input: '../input.js',\n  output: {\n    file: 'output.js',\n    fo"
  },
  {
    "path": "test/node-sass/expected.css",
    "chars": 63,
    "preview": ".rollup .plugin .scss {\n  color: green;\n  user-select: none; }\n"
  },
  {
    "path": "test/node-sass/rollup.config.js",
    "chars": 220,
    "preview": "import scss from '../../index.es.js'\nimport sass from 'node-sass'\n\nexport default {\n  input: '../input.js',\n  output: {\n"
  },
  {
    "path": "test/postcss/expected.css",
    "chars": 91,
    "preview": ".rollup .plugin .scss {\n  color: green;\n  -ms-user-select: none;\n      user-select: none;\n}"
  },
  {
    "path": "test/postcss/rollup.config.js",
    "chars": 366,
    "preview": "import scss from '../../index.es.js'\nimport postcss from 'postcss'\nimport autoprefixer from 'autoprefixer'\n\nexport defau"
  },
  {
    "path": "test/processor/expected.css",
    "chars": 91,
    "preview": ".rollup .plugin .scss {\n  color: green;\n  -ms-user-select: none;\n      user-select: none;\n}"
  },
  {
    "path": "test/processor/rollup.config.js",
    "chars": 479,
    "preview": "import scss from '../../index.es.js'\nimport postcss from 'postcss'\nimport autoprefixer from 'autoprefixer'\n\nexport defau"
  },
  {
    "path": "test/sass/expected.css",
    "chars": 62,
    "preview": ".rollup .plugin .scss {\n  color: green;\n  user-select: none;\n}"
  },
  {
    "path": "test/sass/rollup.config.js",
    "chars": 205,
    "preview": "import scss from '../../index.es.js'\n\nexport default {\n  input: '../input.js',\n  output: {\n    file: 'nested/output.js',"
  },
  {
    "path": "test/sourcemap/expected.css",
    "chars": 102,
    "preview": ".rollup .plugin .scss {\n  color: green;\n  user-select: none;\n}\n\n/*# sourceMappingURL=output.css.map */"
  },
  {
    "path": "test/sourcemap/rollup.config.js",
    "chars": 209,
    "preview": "import scss from '../../index.es.js'\n\nexport default {\n  input: '../input.js',\n  output: {\n    file: 'output.js',\n    fo"
  },
  {
    "path": "tsconfig.json",
    "chars": 355,
    "preview": "{\n  \"display\": \"Node 12\",\n  \"compilerOptions\": {\n    \"lib\": [\"es2019\", \"es2020.promise\", \"es2020.bigint\", \"es2020.string"
  }
]

About this extraction

This page contains the full source code of the thgh/rollup-plugin-scss GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 35 files (30.6 KB), approximately 8.9k tokens, and a symbol index with 23 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!