rollup-plugin-react-scoped-css 1.0.0-alpha.9 → 1.0.1

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,8 +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** >= 16
8
- + **vite** >= 4
7
+ + **node** >= 18
8
+ + **vite** >= 5
9
9
 
10
10
  ## How to install
11
11
 
@@ -40,7 +40,7 @@ export default {
40
40
  };
41
41
  ```
42
42
 
43
- ***Notes:** Because this plugin has been built with a majority of it's usecase with vite, this plugin doesn't handle transpiling LESS, SCSS or other preprocessors. For that reason, you will likely need to add your transpilation plugins before reactScopedCssPlugin.*
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
44
 
45
45
  ### Customizing the plugin
46
46
  There are a few options available to customize how the plugin works
@@ -50,42 +50,55 @@ There are a few options available to customize how the plugin works
50
50
  * Which files should be included and parsed by the plugin
51
51
  * Default: undefined
52
52
  */
53
- include?: FilterPattern
53
+ include?: FilterPattern;
54
54
 
55
55
  /**
56
56
  * Which files should be exluded and that should not be parsed by the plugin
57
57
  * Default: undefined
58
58
  */
59
- exclude?: FilterPattern
59
+ exclude?: FilterPattern;
60
60
 
61
61
  /**
62
- * If you want to customize the stylesheet file pattern
63
- * if undefined or '' is passed, all files will be evaluated
62
+ * If you want regular files to be scoped & global files to be .global.css
63
+ * Default: false
64
+ */
65
+ scopeStyleByDefault?: boolean;
66
+
67
+ /**
68
+ * If you want to customize the pattern for scoped styles.
69
+ * This will only work if scopeStyleByDefault is false
64
70
  * Default: 'scoped'
65
71
  */
66
- styleFileSuffix?: string
72
+ scopedStyleSuffix?: string;
67
73
 
68
74
  /**
69
- * If you want to customize the attribute prefix that is added to the jsx elements
70
- * 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'
71
78
  */
72
- hashPrefix?: string
79
+ globalStyleSuffix?: string;
73
80
 
74
81
  /**
75
- * If you want to customize the preprocessors
76
- * Default: ['scss', 'css', 'sass', 'less']
82
+ * If you want to customize the pattern for style files.
83
+ * Default: ['css', 'scss', 'sass', 'less']
77
84
  */
78
- styleFileExtensions?: string[]
85
+ styleFileExtensions?: string[];
79
86
 
80
87
  /**
81
- * If you have jsx in other file extensions
88
+ * If you want to customize the pattern for jsx files.
82
89
  * Default: ['jsx', 'tsx']
83
90
  */
84
- 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;
85
98
  }
86
99
  ```
87
100
 
88
- ### Advanced rollup usecases
101
+ ### Advanced Rollup usecases
89
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.
90
103
 
91
104
  ```js
@@ -130,7 +143,7 @@ If you want a selector in scoped styles to be "deep", i.e. affecting child compo
130
143
  ```
131
144
  The above will be compiled into:
132
145
  ```css
133
- .a[data-v-f3f3eg9] .b { /* ... */ }
146
+ .a[data-f3f3eg9] .b { /* ... */ }
134
147
  ```
135
148
  Another exepted format, which will generate the same resutl, is:
136
149
  ```scss
@@ -147,4 +160,3 @@ Be careful with descendant selectors in recursive components! For a CSS rule wit
147
160
 
148
161
  ## Contributing
149
162
  Anyone is free to open a PR and contribute to this project... just be civilized!
150
-
@@ -26,19 +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?.data?.type === "PseudoClassSelector") &&
38
- (item?.next?.data?.type === "ClassSelector" ||
39
- item?.next?.data?.type === "AttributeSelector" ||
40
- item?.next?.data?.type === "IdSelector" ||
41
- item?.next?.data?.type === "PseudoClassSelector"));
29
+ const isPseudoSelector = (item) => {
30
+ return (item?.data?.type === "PseudoClassSelector" ||
31
+ item?.data?.type === "PseudoElementSelector");
42
32
  };
43
33
  const isCombinator = (item) => {
44
34
  return item?.data?.type === "Combinator";
@@ -59,34 +49,33 @@ function scopeCss(css, filename, hash) {
59
49
  if (selector.type !== "Selector") {
60
50
  return;
61
51
  }
62
- let hasHitDeep = false;
63
52
  let item = selector.children.head;
64
- while (item !== null || hasHitDeep) {
65
- // Only to satisfy typescript
66
- if (item === null) {
67
- break;
68
- }
69
- if (isScopedAttributeSelector(item, hash)) {
70
- item = item?.next ?? null;
71
- continue;
72
- }
73
- if (item.next && isScopePiercingPseudoSelector(item.next)) {
74
- hasHitDeep = true;
75
- 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);
76
58
  break;
77
59
  }
78
- if (isChainedSelector(item) || isCombinator(item)) {
79
- item = item?.next ?? null;
80
- continue;
60
+ else if (isCombinator(item) || isPseudoSelector(item)) {
61
+ currentChunkIndex += 1;
81
62
  }
82
- if (item?.next === null) {
83
- selector.children.appendData(attributeSelector);
63
+ else if (item.next) {
64
+ itemsToInsertScopeBefore[currentChunkIndex] = item.next;
84
65
  }
85
66
  else {
86
- selector.children.insertData(attributeSelector, item.next);
67
+ selector.children.appendData(attributeSelector);
68
+ break;
87
69
  }
88
70
  item = item?.next ?? null;
89
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
+ });
90
79
  });
91
80
  });
92
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,25 +24,26 @@ const generateHash = (input, seed = 0) => {
23
24
  };
24
25
  function reactScopedCssPlugin(optionsIn = {}) {
25
26
  const options = {
26
- styleFileSuffix: "scoped",
27
- styleFileExtensions: ["scss", "css", "sass", "less"],
27
+ scopeStyleByDefault: false,
28
+ scopedStyleSuffix: "scoped",
29
+ globalStyleSuffix: "global",
30
+ styleFileExtensions: ["css", "scss", "sass", "less"],
28
31
  jsxFileExtensions: ["jsx", "tsx"],
29
32
  ...optionsIn,
30
33
  };
31
- if (!options.styleFileExtensions || !options.styleFileExtensions.length) {
34
+ const { exclude, globalStyleSuffix, hashPrefix, jsxFileExtensions, include, scopeStyleByDefault, scopedStyleSuffix, styleFileExtensions, } = options;
35
+ if (!styleFileExtensions || !styleFileExtensions.length) {
32
36
  throw new Error("You need to provide at least one style file extension");
33
37
  }
34
- if (!options.jsxFileExtensions || !options.jsxFileExtensions.length) {
38
+ if (!jsxFileExtensions || !jsxFileExtensions.length) {
35
39
  throw new Error("You need to provide at least one jsx file extension");
36
40
  }
37
- const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
38
- const scopedCssRegex = options.styleFileSuffix
39
- ? new RegExp(`\.${options.styleFileSuffix}\.(${options.styleFileExtensions.join("|")})$`)
40
- : new RegExp(`\.(${options.styleFileExtensions.join("|")})$`);
41
- const scopedCssInFileRegex = options.styleFileSuffix
42
- ? new RegExp(`\.${options.styleFileSuffix}\.(${options.styleFileExtensions.join("|")})(\"|\')`)
43
- : new RegExp(`\.(${options.styleFileExtensions.join("|")})(\"|\')`);
44
- 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("|")})$`);
45
47
  return [
46
48
  {
47
49
  name: "rollup-plugin-react-scoped-css:pre",
@@ -50,6 +52,9 @@ function reactScopedCssPlugin(optionsIn = {}) {
50
52
  return;
51
53
  }
52
54
  if (scopedCssRegex.test(source) && jsxRegex.test(importer)) {
55
+ if (scopeStyleByDefault && globalCssRegex.test(source)) {
56
+ return;
57
+ }
53
58
  const importerHash = generateHash(importer);
54
59
  const url = (0, path_1.resolve)((0, path_1.dirname)(importer), `${source}?scope=${importerHash}`);
55
60
  return url;
@@ -60,24 +65,41 @@ function reactScopedCssPlugin(optionsIn = {}) {
60
65
  {
61
66
  name: "rollup-plugin-react-scoped-css:post",
62
67
  transform(code, id) {
63
- if (!filter(id)) {
68
+ if (!filter(id) || id.includes("node_modules")) {
64
69
  return;
65
70
  }
66
- if (scopedCssInFileRegex.test(code)) {
67
- const importerHash = generateHash(id);
68
- const program = this.parse(code);
69
- const scopedAttr = options.hashPrefix
70
- ? `data-${options.hashPrefix}-${importerHash}`
71
- : `data-${importerHash}`;
72
- const newAst = (0, ast_program_1.addHashAttributesToJsxTagsAst)(program, scopedAttr);
73
- 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
+ }
74
91
  }
75
- if (scopedCssRegex.test(getFilenameFromPath(id))) {
76
- const importerHash = getHashFromPath(id);
77
- const scopedAttr = options.hashPrefix
78
- ? `data-${options.hashPrefix}-${importerHash}`
79
- : `data-${importerHash}`;
80
- return (0, scope_css_1.scopeCss)(code, getFilenameFromPath(id), scopedAttr);
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
+ }
81
103
  }
82
104
  },
83
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.9",
3
+ "version": "1.0.1",
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,36 +34,36 @@
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.2",
38
38
  "css-tree": "2.3.1",
39
- "escodegen": "2.0.0",
39
+ "escodegen": "2.1.0",
40
40
  "js-xxhash": "2.0.0",
41
- "rollup": "3.10.0"
41
+ "rollup": "4.24.0"
42
42
  },
43
43
  "devDependencies": {
44
- "@babel/core": "7.20.12",
45
- "@babel/preset-env": "7.20.2",
46
- "@babel/preset-react": "7.18.6",
47
- "@babel/preset-typescript": "7.18.6",
44
+ "@babel/core": "7.25.8",
45
+ "@babel/preset-env": "7.25.8",
46
+ "@babel/preset-react": "7.25.7",
47
+ "@babel/preset-typescript": "7.25.7",
48
48
  "@semantic-release/commit-analyzer": "9.0.2",
49
49
  "@semantic-release/git": "10.0.1",
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",
54
- "@types/escodegen": "0.0.7",
55
- "@types/estree": "1.0.0",
56
- "@types/jest": "29.2.5",
53
+ "@types/css-tree": "2.3.8",
54
+ "@types/escodegen": "0.0.10",
55
+ "@types/estree": "1.0.6",
56
+ "@types/jest": "29.5.13",
57
57
  "@typescript-eslint/eslint-plugin": "5.48.1",
58
58
  "@typescript-eslint/parser": "5.48.1",
59
- "acorn": "8.8.1",
59
+ "acorn": "8.12.1",
60
60
  "eslint": "8.32.0",
61
61
  "eslint-config-prettier": "8.6.0",
62
- "eslint-plugin-import": "2.27.4",
62
+ "eslint-plugin-import": "2.31.0",
63
63
  "eslint-plugin-node": "11.1.0",
64
64
  "eslint-plugin-prettier": "4.2.1",
65
- "eslint-plugin-react": "7.32.0",
66
- "jest": "29.3.1",
65
+ "eslint-plugin-react": "7.37.1",
66
+ "jest": "29.7.0",
67
67
  "semantic-release": "22.0.7",
68
68
  "typescript": "4.9.4"
69
69
  }