rollup-plugin-sass icon indicating copy to clipboard operation
rollup-plugin-sass copied to clipboard

feat: output insertStyle as part of rollup bundle

Open marcalexiei opened this issue 5 months ago • 2 comments

  • Followup of #139

  • Related to #158
  • Related to #161
  • Close #157

This PR aims to replace referencing insertStyle file using the path to the dist folder with rollup build hooks. They can generate a separate chunk that is processed as any other js files in the rollup lifecycle. If preserveModules option is used the separated chunk with be created directly inside a _virtual folder rather than inside a node_modules/... folder

The results is something like this:

rollup config
import { defineConfig } from "rollup";
import sass from "rollup-plugin-sass";

export default defineConfig({
  input: "src/index.js",
  output: {
    dir: "dist",
    preserveModules: true,
  },
  plugins: [sass({ insert: true })],
});

dist/_virtual/____insertStyle.js
dist/index.js
dist/actual_a.scss.js
dist/actual_b.scss.js
I added a screenshot to better show the result: Screenshot 2024-09-25 at 17 42 21

Implementation

Using load and resolveId build hooks we can map a special moduleID and when it is loaded we directly return the code of insertStyle function adding a virtual module.

Another benefit of this approach is that the insertStyle function is now imported directly in the source code. This means that the separate build task to have insertStyle generated with ESM can be removed.


[!WARNING] I noticed these issue after finishing #162 so this branch is based on the one of that PR. That PR adds prettier as a formatter so after merging it the diff here should affect less files. Relevant diff can be seen in the feat: output insertStyle as part of rollup bundle commit

marcalexiei avatar Sep 25 '24 17:09 marcalexiei