rollup-plugin-react-scoped-css 1.0.0-alpha.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,57 +4,8 @@
4
4
  While using react in a professional context, I realized that it was lacking the scopped css feature that I learned to love from Vue and Angular. After some reasearch I came across good plugins, but sadly were not compatible with vite and/or rollup. Thus, I decided to create this plugin which was greatly inspired by the amazing work of [gaoxiaoliangz](https://github.com/gaoxiaoliangz) with his [react-scoped-css plugin](https://github.com/gaoxiaoliangz/react-scoped-css).
5
5
 
6
6
  ## Requirements
7
- + **node** >= 20.0.0
8
- + **vite** >= 4.0.0
9
-
10
- ## Usage
11
-
12
- ```jsx
13
- // Component.jsx
14
- import './Component.scoped.scss'
15
-
16
- export default function Sub() {
17
- return (
18
- <div className="wrap">
19
- <h1>My Component</h1>
20
- </div>
21
- )
22
- }
23
- ```
24
-
25
- ```scss
26
- // Component.scoped.scss
27
- .wrap {
28
- width: 500px;
29
- h1 { color: red; }
30
- }
31
- ```
32
- And just like that the styles will be scoped to the component.
33
-
34
- ## Limitations
35
- Due to the way this plugin is working, it will apply the scope to the file and not the component individually... This may differ from other frameworks since they don't really let you define multiple components in the same file. This then means that if you have 2 components in the same file, the styles might conflict.
36
-
37
- ### Deep selector
38
- If you want a selector in scoped styles to be "deep", i.e. affecting child components, you can use the ::deep combinator:
39
- ```css
40
- .a::deep .b { /* ... */ }
41
- ```
42
- The above will be compiled into:
43
- ```css
44
- .a[data-v-f3f3eg9] .b { /* ... */ }
45
- ```
46
- Another exepted format, which will generate the same resutl, is:
47
- ```scss
48
- .a::v-deep .b { /* ... */ }
49
- ```
50
- This is primarly for backwards compatibility, we recommend the `::deep` selector.
51
- ### Dynamically Generated Content
52
- DOM content created with dangerouslySetInnerHTML are not affected by scoped styles, but you can still style them using deep selectors.
53
-
54
- ### Also Keep in Mind
55
- Scoped styles do not eliminate the need for classes. Due to the way browsers render various CSS selectors, p { color: red } will be many times slower when scoped (i.e. when combined with an attribute selector). If you use classes or ids instead, such as in .example { color: red }, then you virtually eliminate that performance hit.
56
-
57
- Be careful with descendant selectors in recursive components! For a CSS rule with the selector .a .b, if the element that matches .a contains a recursive child component, then all .b in that child component will be matched by the rule.
7
+ + **node** >= 18
8
+ + **vite** >= 5
58
9
 
59
10
  ## How to install
60
11
 
@@ -89,6 +40,8 @@ export default {
89
40
  };
90
41
  ```
91
42
 
43
+ ***Notes:** Because this plugin has been built with vite as its primary usecase, it doesn't transpile LESS, SCSS or other preprocessors. For that reason, you will likely need to add your transpilation plugins before reactScopedCssPlugin if you plan on using this without vite.*
44
+
92
45
  ### Customizing the plugin
93
46
  There are a few options available to customize how the plugin works
94
47
  ```ts
@@ -97,42 +50,55 @@ There are a few options available to customize how the plugin works
97
50
  * Which files should be included and parsed by the plugin
98
51
  * Default: undefined
99
52
  */
100
- include?: FilterPattern
53
+ include?: FilterPattern;
101
54
 
102
55
  /**
103
56
  * Which files should be exluded and that should not be parsed by the plugin
104
57
  * Default: undefined
105
58
  */
106
- exclude?: FilterPattern
59
+ exclude?: FilterPattern;
60
+
61
+ /**
62
+ * If you want regular files to be scoped & global files to be .global.css
63
+ * Default: false
64
+ */
65
+ scopeStyleByDefault?: boolean;
107
66
 
108
67
  /**
109
- * If you want to customize the stylesheet file pattern
110
- * if undefined or '' is passed, all files will be evaluated
68
+ * If you want to customize the pattern for scoped styles.
69
+ * This will only work if scopeStyleByDefault is false
111
70
  * Default: 'scoped'
112
71
  */
113
- styleFileSuffix?: string
72
+ scopedStyleSuffix?: string;
114
73
 
115
74
  /**
116
- * If you want to customize the attribute prefix that is added to the jsx elements
117
- * Default: 'v'
75
+ * If you want to customize the pattern for global styles.
76
+ * This will only work if scopeStyleByDefault is true
77
+ * Default: 'global'
118
78
  */
119
- hashPrefix?: string
79
+ globalStyleSuffix?: string;
120
80
 
121
81
  /**
122
- * If you want to customize the preprocessors
123
- * Default: ['scss', 'css', 'sass', 'less']
82
+ * If you want to customize the pattern for style files.
83
+ * Default: ['css', 'scss', 'sass', 'less']
124
84
  */
125
- styleFileExtensions?: string[]
85
+ styleFileExtensions?: string[];
126
86
 
127
87
  /**
128
- * If you have jsx in other file extensions
88
+ * If you want to customize the pattern for jsx files.
129
89
  * Default: ['jsx', 'tsx']
130
90
  */
131
- jsxFileExtensions?: string[]
91
+ jsxFileExtensions?: string[];
92
+
93
+ /**
94
+ * If you want to customize the attribute prefix that is added to the jsx elements
95
+ * Default: 'v'
96
+ */
97
+ hashPrefix?: string;
132
98
  }
133
99
  ```
134
100
 
135
- ### With other rollup plugins
101
+ ### Advanced Rollup usecases
136
102
  Since this plugin works in two parts, you might need to expose the first part, then add any other plugin, and then expose the second part of the plugin. This part is automatically handled with vite thanks to the enforce attribute.
137
103
 
138
104
  ```js
@@ -143,6 +109,54 @@ export default {
143
109
  };
144
110
  ```
145
111
 
112
+ ## Usage
113
+
114
+ ```jsx
115
+ // Component.jsx
116
+ import './Component.scoped.scss'
117
+
118
+ export default function Sub() {
119
+ return (
120
+ <div className="wrap">
121
+ <h1>My Component</h1>
122
+ </div>
123
+ )
124
+ }
125
+ ```
126
+
127
+ ```scss
128
+ // Component.scoped.scss
129
+ .wrap {
130
+ width: 500px;
131
+ h1 { color: red; }
132
+ }
133
+ ```
134
+ And just like that the styles will be scoped to the component.
135
+
136
+ ## Limitations
137
+ Due to the way this plugin is working, it will apply the scope to the file and not the component individually... This may differ from other frameworks since they don't really let you define multiple components in the same file. This then means that if you have 2 components in the same file, the styles might conflict.
138
+
139
+ ### Deep selector
140
+ If you want a selector in scoped styles to be "deep", i.e. affecting child components, you can use the ::deep combinator:
141
+ ```css
142
+ .a::deep .b { /* ... */ }
143
+ ```
144
+ The above will be compiled into:
145
+ ```css
146
+ .a[data-f3f3eg9] .b { /* ... */ }
147
+ ```
148
+ Another exepted format, which will generate the same resutl, is:
149
+ ```scss
150
+ .a::v-deep .b { /* ... */ }
151
+ ```
152
+ This is primarly for backwards compatibility, we recommend the `::deep` selector.
153
+ ### Dynamically Generated Content
154
+ DOM content created with dangerouslySetInnerHTML are not affected by scoped styles, but you can still style them using deep selectors.
155
+
156
+ ### Also Keep in Mind
157
+ Scoped styles do not eliminate the need for classes. Due to the way browsers render various CSS selectors, p { color: red } will be many times slower when scoped (i.e. when combined with an attribute selector). If you use classes or ids instead, such as in .example { color: red }, then you virtually eliminate that performance hit.
158
+
159
+ Be careful with descendant selectors in recursive components! For a CSS rule with the selector .a .b, if the element that matches .a contains a recursive child component, then all .b in that child component will be matched by the rule.
160
+
146
161
  ## Contributing
147
162
  Anyone is free to open a PR and contribute to this project... just be civilized!
148
-
@@ -26,17 +26,9 @@ const isScopePiercingPseudoSelector = (item) => {
26
26
  return (item?.data?.type === "PseudoElementSelector" &&
27
27
  (item?.data?.name === "v-deep" || item?.data?.name === "deep"));
28
28
  };
29
- const isScopedAttributeSelector = (item, hash) => {
30
- return (item?.data?.type === "AttributeSelector" && item?.data?.name?.name === hash);
31
- };
32
- const isChainedSelector = (item) => {
33
- return ((item?.data?.type === "TypeSelector" ||
34
- item?.data?.type === "ClassSelector" ||
35
- item?.data?.type === "AttributeSelector" ||
36
- item?.data?.type === "IdSelector") &&
37
- (item?.next?.data?.type === "ClassSelector" ||
38
- item?.next?.data?.type === "AttributeSelector" ||
39
- item?.next?.data?.type === "IdSelector"));
29
+ const isPseudoSelector = (item) => {
30
+ return (item?.data?.type === "PseudoClassSelector" ||
31
+ item?.data?.type === "PseudoElementSelector");
40
32
  };
41
33
  const isCombinator = (item) => {
42
34
  return item?.data?.type === "Combinator";
@@ -57,34 +49,33 @@ function scopeCss(css, filename, hash) {
57
49
  if (selector.type !== "Selector") {
58
50
  return;
59
51
  }
60
- let hasHitDeep = false;
61
52
  let item = selector.children.head;
62
- while (item !== null || hasHitDeep) {
63
- // Only to satisfy typescript
64
- if (item === null) {
65
- break;
66
- }
67
- if (isScopedAttributeSelector(item, hash)) {
68
- item = item?.next ?? null;
69
- continue;
70
- }
71
- if (item.next && isScopePiercingPseudoSelector(item.next)) {
72
- hasHitDeep = true;
73
- Object.assign(item.next.data, attributeSelector);
53
+ const itemsToInsertScopeBefore = [];
54
+ let currentChunkIndex = 0;
55
+ while (item !== null) {
56
+ if (isScopePiercingPseudoSelector(item)) {
57
+ Object.assign(item.data, attributeSelector);
74
58
  break;
75
59
  }
76
- if (isChainedSelector(item) || isCombinator(item)) {
77
- item = item?.next ?? null;
78
- continue;
60
+ else if (isCombinator(item) || isPseudoSelector(item)) {
61
+ currentChunkIndex += 1;
79
62
  }
80
- if (item?.next === null) {
81
- selector.children.appendData(attributeSelector);
63
+ else if (item.next) {
64
+ itemsToInsertScopeBefore[currentChunkIndex] = item.next;
82
65
  }
83
66
  else {
84
- selector.children.insertData(attributeSelector, item.next);
67
+ selector.children.appendData(attributeSelector);
68
+ break;
85
69
  }
86
70
  item = item?.next ?? null;
87
71
  }
72
+ // This is true if one of the two break statements above was run. Which means we don't want to add to the last one.
73
+ if (itemsToInsertScopeBefore[currentChunkIndex]) {
74
+ itemsToInsertScopeBefore.pop();
75
+ }
76
+ itemsToInsertScopeBefore.forEach((scopePositionItem) => {
77
+ selector.children.insertData(attributeSelector, scopePositionItem);
78
+ });
88
79
  });
89
80
  });
90
81
  return (0, css_tree_1.generate)(ast);
package/dist/index.d.ts CHANGED
@@ -12,26 +12,37 @@ export interface ReactScopedCssPluginOptions {
12
12
  */
13
13
  exclude?: FilterPattern;
14
14
  /**
15
- * If you want to customize the stylesheet file pattern
16
- * if undefined or '' is passed, all files will be evaluated
15
+ * If you want regular files to be scoped & global files to be .global.css
16
+ * Default: false
17
+ */
18
+ scopeStyleByDefault?: boolean;
19
+ /**
20
+ * If you want to customize the pattern for scoped styles.
21
+ * This will only work if scopeStyleByDefault is false
17
22
  * Default: 'scoped'
18
23
  */
19
- styleFileSuffix?: string;
24
+ scopedStyleSuffix?: string;
20
25
  /**
21
- * If you want to customize the attribute prefix that is added to the jsx elements
22
- * Default: 'v'
26
+ * If you want to customize the pattern for global styles.
27
+ * This will only work if scopeStyleByDefault is true
28
+ * Default: 'global'
23
29
  */
24
- hashPrefix?: string;
30
+ globalStyleSuffix?: string;
25
31
  /**
26
- * If you want to customize the stylesheet extensions
27
- * Default: ['scss', 'css', 'sass', 'less']
32
+ * If you want to customize the pattern for style files.
33
+ * Default: ['css', 'scss', 'sass', 'less']
28
34
  */
29
35
  styleFileExtensions?: string[];
30
36
  /**
31
- * If you have jsx in other file extensions
37
+ * If you want to customize the pattern for jsx files.
32
38
  * Default: ['jsx', 'tsx']
33
39
  */
34
40
  jsxFileExtensions?: string[];
41
+ /**
42
+ * If you want to customize the attribute prefix that is added to the jsx elements
43
+ * Default: undefined
44
+ */
45
+ hashPrefix?: string;
35
46
  }
36
47
  export interface VitePartialPlugin extends Plugin {
37
48
  enforce?: "pre" | "post";
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ const pluginutils_1 = require("@rollup/pluginutils");
8
8
  const escodegen_1 = require("escodegen");
9
9
  const ast_program_1 = require("./ast-program");
10
10
  const scope_css_1 = require("./css/scope-css");
11
+ const getImportDeclarationsValue_1 = require("./utils/getImportDeclarationsValue");
11
12
  const getFilenameFromPath = (filePath) => {
12
13
  const parts = filePath.split("/");
13
14
  return parts[parts.length - 1].split("?")[0];
@@ -23,26 +24,26 @@ const generateHash = (input, seed = 0) => {
23
24
  };
24
25
  function reactScopedCssPlugin(optionsIn = {}) {
25
26
  const options = {
26
- hashPrefix: "v",
27
- styleFileSuffix: "scoped",
28
- styleFileExtensions: ["scss", "css", "sass", "less"],
27
+ scopeStyleByDefault: false,
28
+ scopedStyleSuffix: "scoped",
29
+ globalStyleSuffix: "global",
30
+ styleFileExtensions: ["css", "scss", "sass", "less"],
29
31
  jsxFileExtensions: ["jsx", "tsx"],
30
32
  ...optionsIn,
31
33
  };
32
- if (!options.styleFileExtensions || !options.styleFileExtensions.length) {
34
+ const { exclude, globalStyleSuffix, hashPrefix, jsxFileExtensions, include, scopeStyleByDefault, scopedStyleSuffix, styleFileExtensions, } = options;
35
+ if (!styleFileExtensions || !styleFileExtensions.length) {
33
36
  throw new Error("You need to provide at least one style file extension");
34
37
  }
35
- if (!options.jsxFileExtensions || !options.jsxFileExtensions.length) {
38
+ if (!jsxFileExtensions || !jsxFileExtensions.length) {
36
39
  throw new Error("You need to provide at least one jsx file extension");
37
40
  }
38
- const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
39
- const scopedCssRegex = options.styleFileSuffix
40
- ? new RegExp(`\.${options.styleFileSuffix}\.(${options.styleFileExtensions.join("|")})$`)
41
- : new RegExp(`\.(${options.styleFileExtensions.join("|")})$`);
42
- const scopedCssInFileRegex = options.styleFileSuffix
43
- ? new RegExp(`\.${options.styleFileSuffix}\.(${options.styleFileExtensions.join("|")})(\"|\')`)
44
- : new RegExp(`\.(${options.styleFileExtensions.join("|")})(\"|\')`);
45
- const jsxRegex = new RegExp(`\.(${options.jsxFileExtensions.join("|")})$`);
41
+ const filter = (0, pluginutils_1.createFilter)(include, exclude);
42
+ const scopedCssRegex = new RegExp(!scopeStyleByDefault
43
+ ? `([^\.]+\.${scopedStyleSuffix}\.(${styleFileExtensions.join("|")}))$`
44
+ : `([^\.]+\.(${styleFileExtensions.join("|")}))$`);
45
+ const globalCssRegex = new RegExp(`\.${globalStyleSuffix}\.(${styleFileExtensions.join("|")})$`);
46
+ const jsxRegex = new RegExp(`\.(${jsxFileExtensions.join("|")})$`);
46
47
  return [
47
48
  {
48
49
  name: "rollup-plugin-react-scoped-css:pre",
@@ -51,6 +52,9 @@ function reactScopedCssPlugin(optionsIn = {}) {
51
52
  return;
52
53
  }
53
54
  if (scopedCssRegex.test(source) && jsxRegex.test(importer)) {
55
+ if (scopeStyleByDefault && globalCssRegex.test(source)) {
56
+ return;
57
+ }
54
58
  const importerHash = generateHash(importer);
55
59
  const url = (0, path_1.resolve)((0, path_1.dirname)(importer), `${source}?scope=${importerHash}`);
56
60
  return url;
@@ -61,18 +65,41 @@ function reactScopedCssPlugin(optionsIn = {}) {
61
65
  {
62
66
  name: "rollup-plugin-react-scoped-css:post",
63
67
  transform(code, id) {
64
- if (!filter(id)) {
68
+ if (!filter(id) || id.includes("node_modules")) {
65
69
  return;
66
70
  }
67
- if (scopedCssInFileRegex.test(code)) {
68
- const importerHash = generateHash(id);
69
- const program = this.parse(code);
70
- const newAst = (0, ast_program_1.addHashAttributesToJsxTagsAst)(program, `data-${options.hashPrefix}-${importerHash}`);
71
- return (0, escodegen_1.generate)(newAst);
71
+ if (jsxRegex.test(id)) {
72
+ const rootNode = this.parse(code);
73
+ const imports = (0, getImportDeclarationsValue_1.getImportDeclarationsValue)(rootNode);
74
+ const shouldScope = !!imports?.some((match) => {
75
+ if (scopeStyleByDefault) {
76
+ return scopedCssRegex.test(match) && !globalCssRegex.test(match);
77
+ }
78
+ else {
79
+ return scopedCssRegex.test(match);
80
+ }
81
+ });
82
+ if (shouldScope) {
83
+ const importerHash = generateHash(id);
84
+ const scopedAttr = hashPrefix
85
+ ? `data-${hashPrefix}-${importerHash}`
86
+ : `data-${importerHash}`;
87
+ const newAst = (0, ast_program_1.addHashAttributesToJsxTagsAst)(rootNode, scopedAttr);
88
+ const newCode = (0, escodegen_1.generate)(newAst);
89
+ return newCode;
90
+ }
72
91
  }
73
- if (scopedCssRegex.test(getFilenameFromPath(id))) {
74
- const importerHash = getHashFromPath(id);
75
- return (0, scope_css_1.scopeCss)(code, getFilenameFromPath(id), `data-${options.hashPrefix}-${importerHash}`);
92
+ else {
93
+ if (scopedCssRegex.test(getFilenameFromPath(id))) {
94
+ if (scopeStyleByDefault && globalCssRegex.test(id)) {
95
+ return;
96
+ }
97
+ const importerHash = getHashFromPath(id);
98
+ const scopedAttr = options.hashPrefix
99
+ ? `data-${options.hashPrefix}-${importerHash}`
100
+ : `data-${importerHash}`;
101
+ return (0, scope_css_1.scopeCss)(code, getFilenameFromPath(id), scopedAttr);
102
+ }
76
103
  }
77
104
  },
78
105
  },
@@ -0,0 +1,2 @@
1
+ import { AstNode } from "rollup";
2
+ export declare const getImportDeclarationsValue: (root: AstNode) => any[];
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getImportDeclarationsValue = void 0;
4
+ const ast_iterator_1 = require("../ast-iterator");
5
+ const ast_utils_1 = require("../ast.utils");
6
+ const getImportDeclarationsValue = (root) => {
7
+ const urls = [];
8
+ for (const node of (0, ast_iterator_1.astIterator)(root)) {
9
+ if (!(0, ast_utils_1.isNodeImportOrRequire)(node)) {
10
+ continue;
11
+ }
12
+ const src = (0, ast_utils_1.getSrcFromImportOrRequire)(node);
13
+ urls.push(src);
14
+ }
15
+ return urls;
16
+ };
17
+ exports.getImportDeclarationsValue = getImportDeclarationsValue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rollup-plugin-react-scoped-css",
3
- "version": "1.0.0-alpha.8",
3
+ "version": "1.0.0",
4
4
  "description": "A rollup plugin designed to allow scoped css to be run in react (Compatible with vite and rollup)",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -34,11 +34,11 @@
34
34
  },
35
35
  "homepage": "https://github.com/cmseguin/rollup-plugin-react-scoped-css#readme",
36
36
  "dependencies": {
37
- "@rollup/pluginutils": "5.0.2",
37
+ "@rollup/pluginutils": "5.1.0",
38
38
  "css-tree": "2.3.1",
39
39
  "escodegen": "2.0.0",
40
40
  "js-xxhash": "2.0.0",
41
- "rollup": "3.10.0"
41
+ "rollup": "4.6.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@babel/core": "7.20.12",
@@ -50,7 +50,7 @@
50
50
  "@semantic-release/github": "8.0.7",
51
51
  "@semantic-release/npm": "11.0.1",
52
52
  "@semantic-release/release-notes-generator": "10.0.3",
53
- "@types/css-tree": "^2.3.3",
53
+ "@types/css-tree": "2.3.3",
54
54
  "@types/escodegen": "0.0.7",
55
55
  "@types/estree": "1.0.0",
56
56
  "@types/jest": "29.2.5",
@@ -63,7 +63,7 @@
63
63
  "eslint-plugin-node": "11.1.0",
64
64
  "eslint-plugin-prettier": "4.2.1",
65
65
  "eslint-plugin-react": "7.32.0",
66
- "jest": "29.3.1",
66
+ "jest": "^29.7.0",
67
67
  "semantic-release": "22.0.7",
68
68
  "typescript": "4.9.4"
69
69
  }