๐Ÿ“ฆ situ2001 / scoped-rem

๐Ÿ“„ loader.test.ts ยท 205 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205import { describe, it, expect } from 'vitest';
import { webpack, type Stats } from 'webpack';
import { build as tsdownBuild } from 'tsdown';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

async function runWebpack(
  entry: string,
  loaderPath: string
): Promise<{ output: string; stats: Stats }> {
  await tsdownBuild({
    logLevel: 'error',
  });
  // replace /src with /dist in loaderPath
  loaderPath = loaderPath.replace('/src/', '/dist/');
  // replace .ts with .js in loaderPath
  loaderPath = loaderPath.replace('.ts', '.js');

  return new Promise((resolve, reject) => {
    const compiler = webpack({
      mode: 'development',
      entry,
      output: {
        path: join(tmpdir(), 'webpack-test-output'),
        filename: 'bundle.js',
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              'style-loader',
              'css-loader',
              {
                loader: loaderPath,
              },
            ],
          },
        ],
      },
      optimization: {
        minimize: false,
      },
      plugins: [
        {
          apply(compiler) {
            compiler.hooks.emit.tap('CaptureOutputPlugin', (compilation) => {
              const asset = compilation.assets['bundle.js'];
              if (asset) {
                if (typeof asset.source === 'function') {
                  capturedOutput = asset.source().toString();
                  return;
                }

                if (typeof asset.buffer === 'function') {
                  capturedOutput = asset.buffer().toString('utf-8');
                  return;
                }

                throw new Error('Unknown asset source type');
              }
            });
          },
        },
      ],
    });

    let capturedOutput = '';

    if (!compiler) {
      reject(new Error('Failed to create webpack compiler'));
      return;
    }

    compiler.run((err, stats) => {
      if (err) {
        reject(err);
        return;
      }

      if (!stats) {
        reject(new Error('No stats returned'));
        return;
      }

      const info = stats.toJson();

      if (stats.hasErrors()) {
        reject(new Error(info.errors?.[0]?.message || 'Unknown error'));
        return;
      }

      if (!capturedOutput) {
        reject(new Error('Failed to capture bundle output'));
        return;
      }

      compiler.close(() => {
        resolve({ output: capturedOutput, stats });
      });
    });
  });
}

function createTempFiles(cssContent: string, query: string): { jsFile: string; tempDir: string } {
  const tempDir = mkdtempSync(join(tmpdir(), 'scoped-rem-test-'));
  const cssFile = join(tempDir, `test.css`);
  const jsFile = join(tempDir, `entry.js`);

  writeFileSync(cssFile, cssContent);
  const importStatement = `import './test.css${query}';`;
  writeFileSync(jsFile, importStatement);

  return { jsFile, tempDir };
}

describe('scoped-rem-loader', () => {
  it('should export a webpack loader function', async () => {
    const loader = await import('../src/index.js');
    expect(loader.default).toBeDefined();
    expect(typeof loader.default).toBe('function');
  });

  it('should have proper loader signature', async () => {
    const loader = await import('../src/index.js');
    expect(typeof loader.default).toBe('function');
    expect(loader.default.length).toBeGreaterThan(0);
  });
});

describe('webpack integration tests', () => {
  const loaderPath = join(__dirname, '../src/index.ts');

  it('should transform rem units with rem-scoped query', async () => {
    const inputCss = `.component { font-size: 1.2rem; margin: 0.5rem; }`;
    const { jsFile, tempDir } = createTempFiles(inputCss, '?rem-scoped&rootval=26.6667vw');

    try {
      const { output } = await runWebpack(jsFile, loaderPath);

      expect(output).toContain('--rem-relative-base');
      expect(output).toContain('26.6667vw');
      expect(output).toContain('calc(1.2 * var(--rem-relative-base))');
      expect(output).toContain('calc(0.5 * var(--rem-relative-base))');
    } finally {
      rmSync(tempDir, { recursive: true, force: true });
    }
  });

  it('should not transform without rem-scoped query', async () => {
    const inputCss = `.component { font-size: 1.2rem; }`;
    const { jsFile, tempDir } = createTempFiles(inputCss, '');

    try {
      const { output } = await runWebpack(jsFile, loaderPath);

      expect(output).toContain('1.2rem');
      expect(output).not.toContain('calc(');
      expect(output).not.toContain('--rem-relative-base');
    } finally {
      rmSync(tempDir, { recursive: true, force: true });
    }
  });

  it('should support custom variable names and selectors', async () => {
    const inputCss = `.component { font-size: 1.5rem; }`;
    const { jsFile, tempDir } = createTempFiles(
      inputCss,
      '?rem-scoped&rootval=10vw&varname=custom-base&varselector=.my-component'
    );

    try {
      const { output } = await runWebpack(jsFile, loaderPath);

      expect(output).toContain('--custom-base: 10vw');
      expect(output).toContain('calc(1.5 * var(--custom-base))');
      expect(output).not.toContain('--rem-relative-base');

      expect(output).toContain('.my-component { --custom-base: 10vw');
    } finally {
      rmSync(tempDir, { recursive: true, force: true });
    }
  });

  it('should not generate variable declaration if rootval is missing', async () => {
    const inputCss = `.component { font-size: 2rem; }`;
    const { jsFile, tempDir } = createTempFiles(inputCss, '?rem-scoped&varname=base-no-rootval');

    try {
      const { output } = await runWebpack(jsFile, loaderPath);

      expect(output).toContain('calc(2 * var(--base-no-rootval))');
      expect(output).not.toContain('--base-no-rootval:');
      expect(output).not.toContain('{ --base-no-rootval:');
    } finally {
      rmSync(tempDir, { recursive: true, force: true });
    }
  });
});