rollup-plugin-react-scoped-css 0.5.0 → 0.6.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.
@@ -1,20 +0,0 @@
1
- import { readFile } from "fs/promises";
2
- import { resolve } from "path";
3
- import { parse } from "acorn";
4
- import { astTransformer } from "./ast-transformer";
5
-
6
- describe('astTransformer', () => {
7
- it('should iterate through all nodes', async () => {
8
- let iterationCount = 0;
9
- const file = await readFile(resolve(__dirname, './__mocks__/sample-code-file.js'), { encoding: 'utf-8' })
10
- const ast = parse(file, { sourceType: 'module', ecmaVersion: 2022 });
11
-
12
- const newAst = astTransformer(ast, (node) => {
13
- iterationCount++;
14
- expect(node).toBeTruthy();
15
- })
16
-
17
- expect(newAst).toBeDefined();
18
- expect(iterationCount).toBe(28);
19
- });
20
- })
@@ -1,24 +0,0 @@
1
- const isNode = (obj: any) => {
2
- return typeof obj === 'object' &&
3
- typeof (obj as any)?.end === 'number' &&
4
- typeof (obj as any)?.start === 'number' &&
5
- typeof (obj as any)?.type === 'string'
6
- }
7
-
8
- export const astTransformer = (ast: any, callback: Function) => {
9
- for (let key of Object.keys(ast)) {
10
- if (['end', 'start', 'type'].includes(key)) { continue; }
11
-
12
- if (Array.isArray(ast[key])) {
13
- for (let nodeIndex in ast[key]) {
14
- ast[key][nodeIndex] = astTransformer(ast[key][nodeIndex], callback)
15
- }
16
- } else if(isNode(ast[key])) {
17
- ast[key] = astTransformer(ast[key], callback)
18
- }
19
- }
20
-
21
- const result = callback(ast);
22
-
23
- return typeof result !== 'undefined' ? result : ast
24
- }
@@ -1,46 +0,0 @@
1
- import { resolve } from 'path'
2
- import { readFile } from 'fs/promises'
3
- import { parse } from 'acorn'
4
- import { generate } from 'escodegen'
5
- import { addHashAttributesToJsxTagsAst } from './ast.utils'
6
-
7
- describe('AST Utils', () => {
8
- beforeEach(() => {
9
- global.implementation = null
10
- })
11
-
12
- describe('classic implementation', () => {
13
- it('Should add the attr to the right elements', async () => {
14
- const compiled = await readFile(resolve(__dirname, './__mocks__/classic-compiled-jsx.js'), { encoding: 'utf-8' })
15
- const compiledWithAttr = await readFile(resolve(__dirname, './__mocks__/classic-compiled-jsx-with-attr.js'), { encoding: 'utf-8' })
16
- const ast = parse(compiled, { ecmaVersion: 2021, sourceType: "module" })
17
- const modifiedAst = addHashAttributesToJsxTagsAst(ast, 'data-v-123456')
18
- const modifiedCompiled = generate(modifiedAst, { format: {
19
- indent: {
20
- style: ' ',
21
- },
22
- quotes: 'double',
23
- } })
24
-
25
- expect(modifiedCompiled).toEqual(compiledWithAttr)
26
- })
27
- })
28
-
29
- describe('new implementation', () => {
30
- it('Should add the attr to the right elements', async () => {
31
- const compiled = await readFile(resolve(__dirname, './__mocks__/new-compiled-jsx.js'), { encoding: 'utf-8' })
32
- const compiledWithAttr = await readFile(resolve(__dirname, './__mocks__/new-compiled-jsx-with-attr.js'), { encoding: 'utf-8' })
33
- const ast = parse(compiled, { ecmaVersion: 2021, sourceType: "module" })
34
- const modifiedAst = addHashAttributesToJsxTagsAst(ast, 'data-v-123456')
35
- const modifiedCompiled = generate(modifiedAst, { format: {
36
- indent: {
37
- style: ' ',
38
- },
39
- quotes: 'double',
40
- } })
41
-
42
- expect(modifiedCompiled).toEqual(compiledWithAttr)
43
- })
44
- })
45
-
46
- })
package/src/ast.utils.ts DELETED
@@ -1,48 +0,0 @@
1
- import { astIterator } from "./ast-iterator"
2
- import { astTransformer } from "./ast-transformer"
3
- import { ClassicJsxParser } from "./parsers/classic-parser"
4
- import { JsxParser, ParserImplementations } from "./parsers/jsx-parser.model"
5
- import { NewJsxParser } from "./parsers/new-parser"
6
-
7
- declare global {
8
- var implementation: null | ParserImplementations
9
- }
10
-
11
- global.implementation = null
12
-
13
- const classicParser = new ClassicJsxParser()
14
- const newParser = new NewJsxParser()
15
-
16
- let parser: JsxParser = classicParser;
17
-
18
- const findImplementation = (program: any) => {
19
- let implementation: ParserImplementations = ParserImplementations.classic;
20
- for (let node of astIterator(program)) {
21
- if (node.type !== 'ImportDeclaration') {
22
- continue;
23
- }
24
-
25
- if (node.specifiers.some((n: any) => n.local.name === 'jsxRuntime') || node.source.value === 'react/jsx-runtime') {
26
- return ParserImplementations.new
27
- }
28
- }
29
- return implementation
30
- }
31
-
32
- export function addHashAttributesToJsxTagsAst(program: any, attr: string) {
33
-
34
- // Once in the program, we can determine which parser to use
35
- if (global.implementation === null) {
36
- global.implementation = findImplementation(program)
37
-
38
- if (global.implementation === ParserImplementations.new) {
39
- parser = newParser
40
- }
41
- }
42
-
43
- return astTransformer(program, (node: any) => {
44
- if (parser.isNodeReactElement(node) && !parser.isNodeReactFragment(node)) {
45
- return parser.extendNodeWithAttributes(node, attr)
46
- }
47
- })
48
- }
package/src/index.ts DELETED
@@ -1,144 +0,0 @@
1
- import * as path from 'path';
2
- import { xxHash32 } from 'js-xxhash';
3
- import { createFilter, FilterPattern } from '@rollup/pluginutils';
4
- import { compileStyle } from '@vue/component-compiler-utils'
5
- import { generate } from 'escodegen'
6
-
7
- import type { Plugin } from 'rollup'
8
- import { addHashAttributesToJsxTagsAst } from './ast.utils';
9
-
10
- const getFilenameFromPath = (filePath: string) => {
11
- const parts = filePath.split('/')
12
- return parts[parts.length - 1].split('?')[0]
13
- }
14
-
15
- const getHashFromPath = (filePath: string) => {
16
- const search = '?scope='
17
- const hash = filePath.slice(filePath.indexOf(search) + search.length)
18
- return hash
19
- }
20
-
21
- const generateHash = (input: string, seed: number = 0) => {
22
- let hashNum = xxHash32(Buffer.from(input, 'utf8'), seed);
23
- return hashNum.toString(16);
24
- }
25
-
26
- const addAttributesToCss = (src: string, fileName: string, hash: string) => {
27
- const { code } = compileStyle({
28
- source: src,
29
- filename: fileName,
30
- id: hash,
31
- scoped: true,
32
- trim: true,
33
- })
34
-
35
- return code
36
- }
37
-
38
- export interface ReactScopedCssPluginOptions {
39
- /**
40
- * Which files should be included and parsed by the plugin
41
- * Default: undefined
42
- */
43
- include?: FilterPattern
44
-
45
- /**
46
- * Which files should be exluded and that should not be parsed by the plugin
47
- * Default: undefined
48
- */
49
- exclude?: FilterPattern
50
-
51
- /**
52
- * If you want to customize the stylesheet file pattern
53
- * if undefined or '' is passed, all files will be evaluated
54
- * Default: 'scoped'
55
- */
56
- styleFileSuffix?: string
57
-
58
- /**
59
- * If you want to customize the attribute prefix that is added to the jsx elements
60
- * Default: 'v'
61
- */
62
- hashPrefix?: string
63
-
64
- /**
65
- * If you want to customize the stylesheet extensions
66
- * Default: ['scss', 'css', 'sass', 'less']
67
- */
68
- styleFileExtensions?: string[]
69
-
70
- /**
71
- * If you have jsx in other file extensions
72
- * Default: ['jsx', 'tsx']
73
- */
74
- jsxFileExtensions?: string[]
75
- }
76
-
77
- export interface VitePartialPlugin extends Plugin {
78
- enforce?: "pre" | "post"
79
- }
80
-
81
- export default function reactScopedCssPlugin(optionsIn: ReactScopedCssPluginOptions = {}): VitePartialPlugin[] {
82
- const options: Partial<ReactScopedCssPluginOptions> = {
83
- hashPrefix: 'v',
84
- styleFileSuffix: 'scoped',
85
- styleFileExtensions: ['scss', 'css', 'sass', 'less'],
86
- jsxFileExtensions: ['jsx', 'tsx'],
87
- ...optionsIn
88
- }
89
-
90
- if (!options.styleFileExtensions || !options.styleFileExtensions.length) {
91
- throw new Error('You need to provide at least one style file extension')
92
- }
93
-
94
- if (!options.jsxFileExtensions || !options.jsxFileExtensions.length) {
95
- throw new Error('You need to provide at least one jsx file extension')
96
- }
97
-
98
- const filter = createFilter( options.include, options.exclude );
99
- const scopedCssRegex = options.styleFileSuffix
100
- ? new RegExp(`\.${options.styleFileSuffix}\.(${options.styleFileExtensions.join('|')})$`)
101
- : new RegExp(`\.(${options.styleFileExtensions.join('|')})$`)
102
- const scopedCssInFileRegex = options.styleFileSuffix
103
- ? new RegExp(`\.${options.styleFileSuffix}\.(${options.styleFileExtensions.join('|')})(\"|\')`)
104
- : new RegExp(`\.(${options.styleFileExtensions.join('|')})(\"|\')`)
105
- const jsxRegex = new RegExp(`\.(${options.jsxFileExtensions.join('|')})$`)
106
-
107
- return [
108
- {
109
- name: 'rollup-plugin-react-scoped-css:pre',
110
- resolveId(source, importer) {
111
- if (!importer) {
112
- return;
113
- }
114
-
115
- if (scopedCssRegex.test(source) && jsxRegex.test(importer)) {
116
- const importerHash = generateHash(importer);
117
- const url = path.resolve(path.dirname(importer), `${source}?scope=${importerHash}`)
118
- return url
119
- }
120
- },
121
- enforce: 'pre'
122
- },
123
- {
124
- name: 'rollup-plugin-react-scoped-css:post',
125
- transform(code, id) {
126
- if (!filter(id)) {
127
- return;
128
- }
129
-
130
- if (scopedCssInFileRegex.test(code)) {
131
- const importerHash = generateHash(id);
132
- const program = this.parse(code)
133
- const newAst = addHashAttributesToJsxTagsAst(program, `data-${options.hashPrefix}-${importerHash}`)
134
- return generate(newAst)
135
- }
136
-
137
- if (scopedCssRegex.test(getFilenameFromPath(id))) {
138
- const importerHash = getHashFromPath(id);
139
- return addAttributesToCss(code, getFilenameFromPath(id), `data-${options.hashPrefix}-${importerHash}`)
140
- }
141
- }
142
- }
143
- ]
144
- }
@@ -1,58 +0,0 @@
1
- import { JsxParser } from "./jsx-parser.model";
2
-
3
- export class ClassicJsxParser implements JsxParser {
4
- isNodeReactFragment(node: any) {
5
- return node?.arguments?.[0]?.object?.name === "React" &&
6
- node?.arguments?.[0]?.property?.name === "Fragment"
7
- }
8
- isNodeReactElement(node: any) {
9
- return node?.type === 'CallExpression' &&
10
- node?.callee?.object?.name === 'React' &&
11
- node?.callee?.property?.name === 'createElement'
12
- }
13
-
14
- public extendNodeWithAttributes(node: any, attr: string) {
15
- const arg = node?.arguments?.[1]
16
- return {
17
- ...node,
18
- arguments: node?.arguments.map((v: any, i: number) => {
19
- if (i === 1) {
20
- if (v.type === 'ObjectExpression') {
21
- return {
22
- ...v,
23
- properties: [
24
- ...arg.properties,
25
- this.createAttributeNode(attr)
26
- ]
27
- }
28
- } else {
29
- return {
30
- type: 'ObjectExpression',
31
- properties: [this.createAttributeNode(attr)]
32
- }
33
- }
34
- }
35
- return v
36
- })
37
- }
38
- }
39
-
40
- private createAttributeNode(attr: string) {
41
- return {
42
- type: 'Property',
43
- method: false,
44
- shorthand: false,
45
- computed: false,
46
- key: {
47
- type: 'Identifier',
48
- name: `"${attr}"`
49
- },
50
- value: {
51
- type: 'Literal',
52
- value: true,
53
- raw: "true"
54
- },
55
- kind: 'init'
56
- }
57
- }
58
- }
@@ -1,10 +0,0 @@
1
- export interface JsxParser {
2
- isNodeReactElement: (node: any) => boolean
3
- isNodeReactFragment: (node: any) => boolean
4
- extendNodeWithAttributes: (node: any, attr: string) => any
5
- }
6
-
7
- export enum ParserImplementations {
8
- new = 'new',
9
- classic = 'classic'
10
- }
@@ -1,58 +0,0 @@
1
- import { JsxParser } from "./jsx-parser.model";
2
-
3
- export class NewJsxParser implements JsxParser {
4
- isNodeReactFragment(node: any) {
5
- return node.arguments?.[0]?.type === "Identifier" &&
6
- ['_Fragment', 'Fragment'].includes(node.arguments?.[0]?.name)
7
- }
8
-
9
- isNodeReactElement(node: any) {
10
- return node?.type === 'CallExpression' &&
11
- ['_jsxDEV', '_jsx', '_jsxs', 'jsxDev', 'jsx', 'jsxs'].includes(node?.callee?.name)
12
- }
13
-
14
- public extendNodeWithAttributes(node: any, attr: string) {
15
- const arg = node?.arguments?.[1]
16
- return {
17
- ...node,
18
- arguments: node?.arguments.map((v: any, i: number) => {
19
- if (i === 1) {
20
- if (v.type === 'ObjectExpression') {
21
- return {
22
- ...v,
23
- properties: [
24
- ...arg.properties,
25
- this.createAttributeNode(attr)
26
- ]
27
- }
28
- } else {
29
- return {
30
- type: 'ObjectExpression',
31
- properties: [this.createAttributeNode(attr)]
32
- }
33
- }
34
- }
35
- return v
36
- })
37
- }
38
- }
39
-
40
- private createAttributeNode(attr: string) {
41
- return {
42
- type: 'Property',
43
- method: false,
44
- shorthand: false,
45
- computed: false,
46
- key: {
47
- type: 'Identifier',
48
- name: `"${attr}"`
49
- },
50
- value: {
51
- type: 'Literal',
52
- value: true,
53
- raw: "true"
54
- },
55
- kind: 'init'
56
- }
57
- }
58
- }