level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
432
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/css-minimize/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should minimize CSS correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: {}, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; expect(content).toEqual( '.a,.b{font-size:1.5rem;line-height:1.5;text-align:center}.b{background:#fafafa}', ); });
435
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/css-modules-composes/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile CSS modules composes correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; expect(content).toMatch( /.*\{background:red;color:#ff0\}.*\{background:blue\}/, ); }); test('should compile CSS modules composes with external correctly', async () => { const builder = await build({ cwd: __dirname, entry: { external: path.resolve(__dirname, './src/external.js') }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; expect(content).toMatch( /.*\{background:cyan;color:#000\}.*\{background:green\}/, ); });
441
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/css-modules-dom/index.test.ts
import { join, resolve } from 'path'; import { fs } from '@modern-js/utils'; import { build, getHrefByEntryName } from '@scripts/shared'; import { expect, test } from '@modern-js/e2e/playwright'; const fixtures = resolve(__dirname); test('enableCssModuleTSDeclaration', async () => { fs.removeSync(join(fixtures, 'src/App.module.less.d.ts')); fs.removeSync(join(fixtures, 'src/App.module.scss.d.ts')); await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, builderConfig: { output: { enableCssModuleTSDeclaration: true, }, }, }); expect( fs.existsSync(join(fixtures, 'src/App.module.less.d.ts')), ).toBeTruthy(); expect( fs .readFileSync(join(fixtures, 'src/App.module.less.d.ts'), { encoding: 'utf-8', }) .includes(`title: string;`), ).toBeTruthy(); expect( fs.existsSync(join(fixtures, 'src/App.module.scss.d.ts')), ).toBeTruthy(); expect( fs .readFileSync(join(fixtures, 'src/App.module.scss.d.ts'), { encoding: 'utf-8', }) .includes(`header: string;`), ).toBeTruthy(); }); test('disableCssExtract', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, runServer: true, builderConfig: { output: { disableCssExtract: true, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); // disableCssExtract worked const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).filter(file => file.endsWith('.css')); expect(cssFiles.length).toBe(0); // scss worked const header = page.locator('#header'); await expect(header).toHaveCSS('font-size', '20px'); // less worked const title = page.locator('#title'); await expect(title).toHaveCSS('font-size', '20px'); builder.close(); });
449
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/css-modules-global/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile CSS modules with :global() correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; expect(content).toMatch( /.*\{position:relative\}.* \.bar,.* \.baz\{height:100%;overflow:hidden\}.* \.lol{width:80%}/, ); });
452
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/css-modules-ts-declaration/index.test.ts
import { join, resolve } from 'path'; import { fs } from '@modern-js/utils'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; const fixtures = __dirname; const generatorTempDir = async (testDir: string) => { await fs.emptyDir(testDir); await fs.copy(join(fixtures, 'src'), testDir); return () => fs.remove(testDir); }; test('should generator ts declaration correctly for css modules auto true', async () => { const testDir = join(fixtures, 'test-src-1'); const clear = await generatorTempDir(testDir); await build({ cwd: __dirname, entry: { index: resolve(testDir, 'index.js') }, builderConfig: { output: { disableSourceMap: true, enableCssModuleTSDeclaration: true, }, }, }); expect(fs.existsSync(join(testDir, './a.css.d.ts'))).toBeFalsy(); expect(fs.existsSync(join(testDir, './b.module.scss.d.ts'))).toBeTruthy(); expect(fs.existsSync(join(testDir, './c.module.less.d.ts'))).toBeTruthy(); expect(fs.existsSync(join(testDir, './d.global.less.d.ts'))).toBeFalsy(); const content = fs.readFileSync(join(testDir, './b.module.scss.d.ts'), { encoding: 'utf-8', }); expect(content).toMatch(/'the-b-class': string;/); expect(content).toMatch(/theBClass: string;/); expect(content).toMatch(/primary: string;/); expect(content).toMatch(/btn: string;/); await clear(); }); test('should generator ts declaration correctly for css modules auto function', async () => { const testDir = join(fixtures, 'test-src-2'); const clear = await generatorTempDir(testDir); await build({ cwd: __dirname, entry: { index: resolve(testDir, 'index.js') }, builderConfig: { output: { disableSourceMap: true, enableCssModuleTSDeclaration: true, cssModules: { auto: path => { return path.endsWith('.less'); }, }, }, }, }); expect(fs.existsSync(join(testDir, './a.css.d.ts'))).toBeFalsy(); expect(fs.existsSync(join(testDir, './b.module.scss.d.ts'))).toBeFalsy(); expect(fs.existsSync(join(testDir, './c.module.less.d.ts'))).toBeTruthy(); expect(fs.existsSync(join(testDir, './d.global.less.d.ts'))).toBeTruthy(); await clear(); }); test('should generator ts declaration correctly for css modules auto Regexp', async () => { const testDir = join(fixtures, 'test-src-3'); const clear = await generatorTempDir(testDir); await build({ cwd: __dirname, entry: { index: resolve(testDir, 'index.js') }, builderConfig: { output: { disableSourceMap: true, enableCssModuleTSDeclaration: true, cssModules: { auto: /\.module\./i, }, }, }, }); expect(fs.existsSync(join(testDir, './a.css.d.ts'))).toBeFalsy(); expect(fs.existsSync(join(testDir, './b.module.scss.d.ts'))).toBeTruthy(); expect(fs.existsSync(join(testDir, './c.module.less.d.ts'))).toBeTruthy(); expect(fs.existsSync(join(testDir, './d.global.less.d.ts'))).toBeFalsy(); await clear(); }); test('should generator ts declaration correctly for custom exportLocalsConvention', async () => { const testDir = join(fixtures, 'test-src-4'); const clear = await generatorTempDir(testDir); await build({ cwd: __dirname, entry: { index: resolve(testDir, 'index.js') }, builderConfig: { output: { disableSourceMap: true, enableCssModuleTSDeclaration: true, cssModules: { auto: /\.module\./i, exportLocalsConvention: 'asIs', }, }, }, }); expect(fs.existsSync(join(testDir, './b.module.scss.d.ts'))).toBeTruthy(); const content = fs.readFileSync(join(testDir, './b.module.scss.d.ts'), { encoding: 'utf-8', }); expect(content).toMatch(/'the-b-class': string;/); expect(content).not.toMatch(/'theBClass': string;/); await clear(); });
459
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/css-modules/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile CSS modules correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { output: { disableSourceMap: true, }, }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; if (builder.providerType === 'rspack') { expect(content).toEqual( '.the-a-class{color:red}.the-b-class-_6773e{color:blue}.the-c-class-c855fd{color:#ff0}.the-d-class{color:green}', ); } else { expect(content).toEqual( '.the-a-class{color:red}.the-b-class-_HnKpz{color:blue}.the-c-class-e94QZl{color:#ff0}.the-d-class{color:green}', ); } }); test('should treat normal CSS as CSS modules when disableCssModuleExtension is true', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { output: { disableSourceMap: true, disableCssModuleExtension: true, }, }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; if (builder.providerType === 'rspack') { expect(content).toEqual( '.the-a-class-_932a3{color:red}.the-b-class-_6773e{color:blue}.the-c-class-c855fd{color:#ff0}.the-d-class{color:green}', ); } else { expect(content).toEqual( '.the-a-class-azoWcU{color:red}.the-b-class-_HnKpz{color:blue}.the-c-class-e94QZl{color:#ff0}.the-d-class{color:green}', ); } }); test('should compile CSS modules follow by output.cssModules', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { output: { cssModules: { auto: resource => { return resource.includes('.scss'); }, }, disableSourceMap: true, }, }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; if (builder.providerType === 'rspack') { expect(content).toEqual( '.the-a-class{color:red}.the-b-class-_6773e{color:blue}.the-c-class{color:#ff0}.the-d-class{color:green}', ); } else { expect(content).toEqual( '.the-a-class{color:red}.the-b-class-_HnKpz{color:blue}.the-c-class{color:#ff0}.the-d-class{color:green}', ); } });
465
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/css-nesting/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile CSS nesting correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; expect(content).toEqual( '.card h1,.card h2,h3 .card{color:red}.card :is(h1){color:blue}.card .foo{font-size:12px}.card .bar{font-size:14px}.card.baz{font-size:16px}.demo:hover{color:green}.demo :hover{color:cyan}.demo .lg .circle,.demo .lg .triangle{opacity:.25}', ); });
468
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/import-common-css/index.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile common css import correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { source: { alias: { '@': './src', }, }, }, }); const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).find(file => file.endsWith('.css'))!; expect(files[cssFiles]).toEqual( 'html{min-height:100%}#a{color:red}#b{color:blue}', ); });
473
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/import-loaders/index.test.ts
import path from 'path'; import { expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { webpackOnlyTest } from '../../../scripts/helper'; webpackOnlyTest( 'should compile CSS modules which depends on importLoaders correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { output: { disableSourceMap: true, }, }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; expect(content).toEqual( '.class-foo-yQ8Tl7+.hello-class-foo{background-color:red}.class-bar-TVH2T6 .hello-class-bar{background-color:blue}', ); }, );
477
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/less-exclude/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should exclude specified less file', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { tools: { less: (opts, { addExcludes }) => { addExcludes([/b\.less$/]); }, }, output: { enableAssetFallback: true, }, }, }); const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).filter(file => file.endsWith('.css')); const lessFiles = Object.keys(files).filter(file => file.endsWith('.less')); expect(lessFiles.length).toBe(1); expect(cssFiles.length).toBe(1); });
481
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/less-import/index.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile less import correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).find(file => file.endsWith('.css'))!; expect(files[cssFiles]).toEqual('body{background-color:red}'); });
485
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/less-inline-js/index.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile less inline js correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).find(file => file.endsWith('.css'))!; expect(files[cssFiles]).toEqual('body{width:200}'); });
488
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/less-npm-import/index.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { fs } from '@modern-js/utils'; test('should compile less npm import correctly', async () => { fs.copySync( path.resolve(__dirname, '_node_modules'), path.resolve(__dirname, 'node_modules'), ); const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).find(file => file.endsWith('.css'))!; expect(files[cssFiles]).toEqual('html{height:100%}body{color:red}'); });
492
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/multi-css/index.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should emit multiple css files correctly', async () => { const builder = await build({ cwd: __dirname, entry: { entry1: path.resolve(__dirname, './src/entry1/index.js'), entry2: path.resolve(__dirname, './src/entry2/index.js'), entry3: path.resolve(__dirname, './src/entry3/index.js'), }, }); const files = await builder.unwrapOutputJSON(); const entry1CSS = Object.keys(files).find( file => file.includes('entry1') && file.endsWith('.css'), )!; const entry2CSS = Object.keys(files).find( file => file.includes('entry2') && file.endsWith('.css'), )!; const entry3CSS = Object.keys(files).find( file => file.includes('entry3') && file.endsWith('.css'), )!; expect(files[entry1CSS]).toContain('#entry1{color:red}'); expect(files[entry2CSS]).toContain('#entry2{color:blue}'); expect(files[entry3CSS]).toContain('#entry3{color:green}'); });
499
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/nested-npm-import/index.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { fs } from '@modern-js/utils'; test('should compile nested npm import correctly', async () => { fs.copySync( path.resolve(__dirname, '_node_modules'), path.resolve(__dirname, 'node_modules'), ); const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).find(file => file.endsWith('.css'))!; expect(files[cssFiles]).toEqual( '#b{color:#ff0}#c{color:green}#a{font-size:10px}html{font-size:18px}', ); });
505
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/relative-import/index.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile CSS relative imports correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; expect(content).toContain('.foo{color:red}.bar{color:blue}.baz{color:green}'); });
513
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/resolve-alias/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile CSS with alias correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { source: { alias: { '@common': path.resolve(__dirname, 'src/common'), }, }, }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; if (builder.providerType === 'rspack') { expect(content).toEqual( '.the-a-class{color:red}.the-a-class,.the-b-class{background-image:url(/static/image/icon.c6be40ea.png)}.the-b-class{color:blue}.the-c-class{background-image:url(/static/image/icon.c6be40ea.png);color:#ff0}', ); } else { expect(content).toEqual( '.the-a-class{color:red}.the-a-class,.the-b-class{background-image:url(/static/image/icon.6c12aba3.png)}.the-b-class{color:blue}.the-c-class{background-image:url(/static/image/icon.6c12aba3.png);color:#ff0}', ); } });
518
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/resolve-url-loader/index.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should resolve relative asset correctly in SCSS file', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; expect(content).toContain('background-image:url(/static/image/icon'); });
522
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/sass-exclude/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should exclude specified scss file', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { tools: { sass: (opts, { addExcludes }) => { addExcludes([/b\.scss$/]); }, }, output: { enableAssetFallback: true, }, }, }); const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).filter(file => file.endsWith('.css')); const scssFiles = Object.keys(files).filter(file => file.endsWith('.scss')); expect(scssFiles.length).toBe(1); expect(cssFiles.length).toBe(1); });
526
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/css/style-loader/index.test.ts
import { join } from 'path'; import { build, getHrefByEntryName } from '@scripts/shared'; import { expect, test } from '@modern-js/e2e/playwright'; const fixtures = __dirname; test('should inline style when disableCssExtract is false', async ({ page, }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, runServer: true, builderConfig: { output: { disableCssExtract: true, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); // disableCssExtract worked const files = await builder.unwrapOutputJSON(); const cssFiles = Object.keys(files).filter(file => file.endsWith('.css')); expect(cssFiles.length).toBe(0); // should inline minified css const mainJsFile = Object.keys(files).find(file => file.includes('main.'))!; expect( files[mainJsFile].includes( 'body,html{margin:0;padding:0}*{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;box-sizing:border-box}', ), ).toBeTruthy(); // scss worked const header = page.locator('#header'); await expect(header).toHaveCSS('font-size', '20px'); // less worked const title = page.locator('#header'); await expect(title).toHaveCSS('font-size', '20px'); builder.close(); });
534
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/decorator
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/decorator/common/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; test('decorator legacy(default)', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, runServer: true, builderConfig: {}, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.aaa')).toBe('hello!'); expect(await page.evaluate('window.bbb')).toBe('world'); builder.close(); }); test('decorator latest', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, runServer: true, builderConfig: { output: { enableLatestDecorators: true, }, }, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.aaa')).toBe('hello!'); expect(await page.evaluate('window.bbb')).toBe('world'); builder.close(); });
536
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/decorator
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/decorator/latest/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; test('decorator latest', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, runServer: true, builderConfig: { output: { enableLatestDecorators: true, }, }, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.aaa')).toBe('hello world'); // swc... if (builder.providerType !== 'rspack') { expect(await page.evaluate('window.bbb')).toContain( "Cannot assign to read only property 'message' of object", ); expect(await page.evaluate('window.ccc')).toContain( "Cannot assign to read only property 'message' of object", ); } builder.close(); });
538
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/decorator
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/decorator/legacy/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; test('decorator legacy(default)', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, runServer: true, builderConfig: {}, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.aaa')).toBe('hello world'); if (builder.providerType !== 'rspack') { expect(await page.evaluate('window.ccc')).toContain( "Cannot assign to read only property 'message' of object", ); } builder.close(); });
540
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/dev/dev.test.ts
import { join } from 'path'; import { fs } from '@modern-js/utils'; import { expect, test } from '@modern-js/e2e/playwright'; import { dev, getHrefByEntryName } from '@scripts/shared'; const fixtures = __dirname; // hmr test will timeout in CI test.skip('default & hmr (default true)', async ({ page }) => { await fs.copy(join(fixtures, 'hmr/src'), join(fixtures, 'hmr/test-src')); const builder = await dev({ cwd: join(fixtures, 'hmr'), entry: { main: join(fixtures, 'hmr', 'test-src/index.ts'), }, builderConfig: { tools: { devServer: { client: { host: '', port: '', }, }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const locator = page.locator('#test'); await expect(locator).toHaveText('Hello Builder!'); await expect(locator).toHaveCSS('color', 'rgb(255, 0, 0)'); const appPath = join(fixtures, 'hmr', 'test-src/App.tsx'); await fs.writeFile( appPath, fs.readFileSync(appPath, 'utf-8').replace('Hello Builder', 'Hello Test'), ); // wait for hmr take effect await new Promise(resolve => setTimeout(resolve, 2000)); await expect(locator).toHaveText('Hello Test!'); const cssPath = join(fixtures, 'hmr', 'test-src/App.css'); await fs.writeFile( cssPath, `#test { color: rgb(0, 0, 255); }`, ); // wait for hmr take effect await new Promise(resolve => setTimeout(resolve, 2000)); await expect(locator).toHaveCSS('color', 'rgb(0, 0, 255)'); // restore await fs.writeFile( appPath, fs.readFileSync(appPath, 'utf-8').replace('Hello Test', 'Hello Builder'), ); await fs.writeFile( cssPath, `#test { color: rgb(255, 0, 0); }`, ); await builder.server.close(); }); test('dev.port & output.distPath', async ({ page }) => { const builder = await dev({ cwd: join(fixtures, 'basic'), entry: { main: join(fixtures, 'basic', 'src/index.ts'), }, builderConfig: { dev: { port: 3000, }, output: { distPath: { root: 'dist-1', js: 'aa/js', }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); expect(builder.port).toBe(3000); expect( fs.existsSync(join(fixtures, 'basic/dist-1/html/main/index.html')), ).toBeTruthy(); expect(fs.existsSync(join(fixtures, 'basic/dist-1/aa/js'))).toBeTruthy(); const locator = page.locator('#test'); await expect(locator).toHaveText('Hello Builder!'); await builder.server.close(); await fs.remove(join(fixtures, 'basic/dist-1')); }); test.skip('hmr should work when setting dev.port & serverOptions.dev.client', async ({ page, }) => { await fs.copy(join(fixtures, 'hmr/src'), join(fixtures, 'hmr/test-src-1')); const cwd = join(fixtures, 'hmr'); const builder = await dev({ cwd, entry: { main: join(cwd, 'test-src-1/index.ts'), }, builderConfig: { dev: { port: 3001, }, }, serverOptions: { dev: { client: { host: '', }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); expect(builder.port).toBe(3001); const appPath = join(fixtures, 'hmr', 'test-src-1/App.tsx'); const locator = page.locator('#test'); await expect(locator).toHaveText('Hello Builder!'); await fs.writeFile( appPath, fs.readFileSync(appPath, 'utf-8').replace('Hello Builder', 'Hello Test'), ); // wait for hmr take effect await new Promise(resolve => setTimeout(resolve, 2000)); await expect(locator).toHaveText('Hello Test!'); // restore await fs.writeFile( appPath, fs.readFileSync(appPath, 'utf-8').replace('Hello Test', 'Hello Builder'), ); await builder.server.close(); }); // need devcert test.skip('dev.https', async () => { const builder = await dev({ cwd: join(fixtures, 'basic'), entry: { main: join(join(fixtures, 'basic'), 'src/index.ts'), }, builderConfig: { dev: { https: true, }, }, }); expect(builder.urls[0].startsWith('https')).toBeTruthy(); await builder.server.close(); }); // hmr will timeout in CI test.skip('tools.devServer', async ({ page }) => { let i = 0; let reloadFn: undefined | (() => void); // Only tested to see if it works, not all configurations. const builder = await dev({ cwd: join(fixtures, 'basic'), entry: { main: join(join(fixtures, 'basic'), 'src/index.ts'), }, builderConfig: { tools: { devServer: { setupMiddlewares: [ (_middlewares, server) => { reloadFn = () => server.sockWrite('content-changed'); }, ], before: [ (req, res, next) => { i++; next(); }, ], }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const locator = page.locator('#test'); await expect(locator).toHaveText('Hello Builder!'); expect(i).toBeGreaterThanOrEqual(1); expect(reloadFn).toBeDefined(); i = 0; reloadFn!(); // wait for page reload take effect await new Promise(resolve => setTimeout(resolve, 2000)); expect(i).toBeGreaterThanOrEqual(1); await builder.server.close(); });
541
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/dev/history-api-fallback.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { dev } from '@scripts/shared'; const cwd = join(__dirname, 'history-api-fallback'); test('should provide history api fallback correctly', async ({ page }) => { const builder = await dev({ cwd, entry: { main: join(cwd, 'src/index.tsx'), }, builderConfig: { tools: { devServer: { historyApiFallback: true, }, }, }, }); await page.goto(`http://localhost:${builder.port}`); expect(await page.innerHTML('body')).toContain('<div>home<div>'); await page.goto(`http://localhost:${builder.port}/a`); expect(await page.innerHTML('body')).toContain('<div>A</div>'); await page.goto(`http://localhost:${builder.port}/b`); expect(await page.innerHTML('body')).toContain('<div>B</div>'); await builder.server.close(); });
542
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/dev/write-to-disk.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { dev, getHrefByEntryName } from '@scripts/shared'; const fixtures = __dirname; test('writeToDisk default', async ({ page }) => { const builder = await dev({ cwd: join(fixtures, 'basic'), entry: { main: join(fixtures, 'basic', 'src/index.ts'), }, builderConfig: { tools: { devServer: { client: { host: '', port: '', }, }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const locator = page.locator('#test'); await expect(locator).toHaveText('Hello Builder!'); await builder.server.close(); }); test('writeToDisk false', async ({ page }) => { const builder = await dev({ cwd: join(fixtures, 'basic'), entry: { main: join(fixtures, 'basic', 'src/index.ts'), }, builderConfig: { tools: { devServer: { devMiddleware: { writeToDisk: false, }, }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const locator = page.locator('#test'); await expect(locator).toHaveText('Hello Builder!'); await builder.server.close(); }); test('writeToDisk true', async ({ page }) => { const builder = await dev({ cwd: join(fixtures, 'basic'), entry: { main: join(fixtures, 'basic', 'src/index.ts'), }, builderConfig: { tools: { devServer: { devMiddleware: { writeToDisk: true, }, }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const test = page.locator('#test'); await expect(test).toHaveText('Hello Builder!'); await builder.server.close(); });
553
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/externalHelpers/index.test.ts
import path from 'path'; import { build } from '@scripts/shared'; import { providerType } from '@scripts/helper'; import { expect, test } from '@modern-js/e2e/playwright'; import { builderPluginSwc } from '@modern-js/builder-plugin-swc'; test('should externalHelpers by default', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/main.ts') }, plugins: providerType === 'rspack' ? [] : [builderPluginSwc()], }); const files = await builder.unwrapOutputJSON(false); const content = files[ Object.keys(files).find( file => file.includes('static/js') && file.endsWith('.js.map'), )! ]; expect(content).toContain('@swc/helpers'); });
555
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html-tags/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; const isHtmlMatch = (html: string, pattern: RegExp): boolean => Boolean(html.match(pattern)); test('should inject tags', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts') }, builderConfig: { html: { tags: [ { tag: 'script', attrs: { src: 'foo.js' } }, { tag: 'script', attrs: { src: 'https://www.cdn.com/foo.js' } }, { tag: 'script', attrs: { src: 'bar.js' }, append: false }, { tag: 'script', attrs: { src: 'baz.js' }, append: false }, { tag: 'meta', attrs: { name: 'referrer', content: 'origin' } }, ], }, }, }); const files = await builder.unwrapOutputJSON(); const indexHtml = files[path.resolve(__dirname, './dist/html/index/index.html')]; expect(isHtmlMatch(indexHtml, /foo\.js/)).toBeTruthy(); expect( isHtmlMatch(indexHtml, /src="https:\/\/www\.cdn\.com\/foo\.js/), ).toBeTruthy(); expect(isHtmlMatch(indexHtml, /content="origin"/)).toBeTruthy(); });
559
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html/html.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { fs } from '@modern-js/utils'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = __dirname; test.describe('html configure multi', () => { let builder: Awaited<ReturnType<typeof build>>; test.beforeAll(async () => { builder = await build({ cwd: join(fixtures, 'mount-id'), entry: { main: join(join(fixtures, 'mount-id'), 'src/index.ts'), }, runServer: true, builderConfig: { html: { mountId: 'app', }, }, }); }); test.afterAll(() => { builder.close(); }); test('mountId', async ({ page }) => { await page.goto(getHrefByEntryName('main', builder.port)); const test = page.locator('#test'); await expect(test).toHaveText('Hello Builder!'); }); test('title default', async ({ page }) => { await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.evaluate(`document.title`)).resolves.toBe(''); }); test('inject default (head)', async () => { const pagePath = join(builder.distPath, 'html/main/index.html'); const content = await fs.readFile(pagePath, 'utf-8'); expect( /<head>[\s\S]*<script[\s\S]*>[\s\S]*<\/head>/.test(content), ).toBeTruthy(); expect( /<body>[\s\S]*<script[\s\S]*>[\s\S]*<\/body>/.test(content), ).toBeFalsy(); }); }); test.describe('html element set', () => { let builder: Awaited<ReturnType<typeof build>>; let mainContent: string; let fooContent: string; test.beforeAll(async () => { builder = await build({ cwd: join(fixtures, 'template'), entry: { main: join(join(fixtures, 'template'), 'src/index.ts'), foo: join(fixtures, 'template/src/index.ts'), }, runServer: true, builderConfig: { html: { meta: { description: 'a description of the page', }, inject: 'body', crossorigin: 'anonymous', appIcon: './src/assets/icon.png', favicon: './src/assets/icon.png', }, }, }); mainContent = await fs.readFile( join(builder.distPath, 'html/main/index.html'), 'utf-8', ); fooContent = await fs.readFile( join(builder.distPath, 'html/foo/index.html'), 'utf-8', ); }); test.afterAll(() => { builder.close(); }); test('appicon', async () => { const [, iconRelativePath] = /<link.*rel="apple-touch-icon".*href="(.*?)">/.exec(mainContent) || []; expect(iconRelativePath).toBeDefined(); const iconPath = join(builder.distPath, iconRelativePath); expect(fs.existsSync(iconPath)).toBeTruthy(); // should work on all page expect( /<link.*rel="apple-touch-icon".*href="(.*?)">/.test(fooContent), ).toBeTruthy(); }); test('favicon', async () => { const [, iconRelativePath] = /<link.*rel="icon".*href="(.*?)">/.exec(mainContent) || []; expect(iconRelativePath).toBeDefined(); const iconPath = join(builder.distPath, iconRelativePath); expect(fs.existsSync(iconPath)).toBeTruthy(); // should work on all page expect(/<link.*rel="icon".*href="(.*?)">/.test(fooContent)).toBeTruthy(); }); test('custom inject', async () => { expect( /<head>[\s\S]*<script[\s\S]*>[\s\S]*<\/head>/.test(mainContent), ).toBeFalsy(); expect( /<body>[\s\S]*<script[\s\S]*>[\s\S]*<\/body>/.test(mainContent), ).toBeTruthy(); }); test('custom meta', async () => { expect( /<meta name="description" content="a description of the page">/.test( mainContent, ), ).toBeTruthy(); }); test('custom crossorigin', async () => { const allScripts = /(<script [\s\S]*?>)/g.exec(mainContent); expect( allScripts?.every(data => data.includes('crossorigin="anonymous"')), ).toBeTruthy(); }); }); test('custom title', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'template'), entry: { main: join(join(fixtures, 'template'), 'src/index.ts'), }, runServer: true, builderConfig: { html: { title: 'custom title', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.evaluate(`document.title`)).resolves.toBe('custom title'); builder.close(); }); test('template & templateParameters', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'template'), entry: { main: join(join(fixtures, 'template'), 'src/index.ts'), }, runServer: true, builderConfig: { html: { template: './static/index.html', templateParameters: { foo: 'bar', }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.evaluate(`document.title`)).resolves.toBe( 'custom template', ); const testTemplate = page.locator('#test-template'); await expect(testTemplate).toHaveText('xxx'); const testEl = page.locator('#test'); await expect(testEl).toHaveText('Hello Builder!'); await expect(page.evaluate(`window.foo`)).resolves.toBe('bar'); builder.close(); }); test('templateByEntries & templateParametersByEntries', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'template'), entry: { main: join(fixtures, 'template/src/index.ts'), foo: join(fixtures, 'template/src/index.ts'), bar: join(fixtures, 'template/src/index.ts'), }, runServer: true, builderConfig: { html: { templateByEntries: { foo: './static/foo.html', bar: './static/bar.html', }, templateParametersByEntries: { foo: { type: 'foo', }, bar: { type: 'bar', }, }, }, }, }); await page.goto(getHrefByEntryName('foo', builder.port)); const testTemplate = page.locator('#test-template'); await expect(testTemplate).toHaveText('foo'); await expect(page.evaluate(`window.type`)).resolves.toBe('foo'); await page.goto(getHrefByEntryName('bar', builder.port)); await expect(testTemplate).toHaveText('bar'); await expect(page.evaluate(`window.type`)).resolves.toBe('bar'); builder.close(); }); test('title & titleByEntries & templateByEntries', async ({ page }) => { // priority: template title > titleByEntries > title const builder = await build({ cwd: join(fixtures, 'template'), entry: { main: join(fixtures, 'template/src/index.ts'), foo: join(fixtures, 'template/src/index.ts'), bar: join(fixtures, 'template/src/index.ts'), }, runServer: true, builderConfig: { html: { title: 'custom title', titleByEntries: { foo: 'Tiktok', }, templateByEntries: { bar: './static/index.html', }, templateParameters: { foo: 'bar', }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.evaluate(`document.title`)).resolves.toBe('custom title'); await page.goto(getHrefByEntryName('foo', builder.port)); await expect(page.evaluate(`document.title`)).resolves.toBe('Tiktok'); await page.goto(getHrefByEntryName('bar', builder.port)); await expect(page.evaluate(`document.title`)).resolves.toBe( 'custom template', ); builder.close(); }); test('disableHtmlFolder', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'template'), entry: { main: join(join(fixtures, 'template'), 'src/index.ts'), }, runServer: true, builderConfig: { html: { disableHtmlFolder: true, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const pagePath = join(builder.distPath, 'html/main.html'); expect(fs.existsSync(pagePath)).toBeTruthy(); builder.close(); }); test('tools.htmlPlugin', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'template'), entry: { main: join(join(fixtures, 'template'), 'src/index.ts'), }, runServer: true, builderConfig: { tools: { htmlPlugin(config, { entryName }) { if (entryName === 'main') { config.scriptLoading = 'module'; } }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const pagePath = join(builder.distPath, 'html/main/index.html'); const content = await fs.readFile(pagePath, 'utf-8'); const allScripts = /(<script [\s\S]*?>)/g.exec(content); expect( allScripts?.every(data => data.includes('type="module"')), ).toBeTruthy(); builder.close(); });
560
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html/app-icon/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should emit app icon to dist path', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { html: { appIcon: './src/icon.png', }, }, }); const files = await builder.unwrapOutputJSON(); expect( Object.keys(files).some(file => file.endsWith('static/image/icon.png')), ).toBeTruthy(); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; expect(html).toContain( '<link rel="apple-touch-icon" sizes="180*180" href="/static/image/icon.png">', ); }); test('should apply asset prefix to app icon URL', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { html: { appIcon: './src/icon.png', }, output: { assetPrefix: 'https://www.example.com', }, }, }); const files = await builder.unwrapOutputJSON(); const { origin: { bundlerConfigs }, } = await builder.instance.inspectConfig(); expect(bundlerConfigs[0].output.publicPath).toBe('https://www.example.com/'); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; expect(html).toContain( '<link rel="apple-touch-icon" sizes="180*180" href="https://www.example.com/static/image/icon.png">', ); });
562
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html/favicon/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should emit local favicon to dist path', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { html: { favicon: './src/icon.png', }, }, }); const files = await builder.unwrapOutputJSON(); expect( Object.keys(files).some(file => file.endsWith('/icon.png')), ).toBeTruthy(); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; expect(html).toContain('<link rel="icon" href="/icon.png">'); }); test('should apply asset prefix to favicon URL', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { html: { favicon: './src/icon.png', }, output: { assetPrefix: 'https://www.example.com', }, }, }); const files = await builder.unwrapOutputJSON(); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; expect(html).toContain( '<link rel="icon" href="https://www.example.com/icon.png">', ); }); test('should allow favicon to be a CDN URL', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { html: { favicon: 'https://foo.com/icon.png', }, }, }); const files = await builder.unwrapOutputJSON(); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; expect(html).toContain('<link rel="icon" href="https://foo.com/icon.png">'); });
564
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html/inject-false/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('builder injection script order should be as expected', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { html: { inject: false, template: './static/index.html', }, output: { assetsRetry: { inlineScript: false, }, disableInlineRuntimeChunk: true, convertToRem: { inlineRuntime: false, }, }, }, }); const files = await builder.unwrapOutputJSON(); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; // assetsRetry => rem => normal resource => template custom resource expect( /(<script src="\/static\/js\/assets-retry).*(<script src="\/static\/js\/convert-rem).*(\/static\/js\/index).*(example.com\/assets\/a.js)/.test( html, ), ).toBeTruthy(); });
568
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html/minify/index.swc.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { builderPluginSwc } from '@modern-js/builder-plugin-swc'; const fixtures = __dirname; test('should minify template js & css correctly when use swc-plugin', async ({ page, }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, runServer: true, plugins: [builderPluginSwc()], builderConfig: { html: { template: './static/index.html', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const test = page.locator('#test'); await expect(test).toHaveCSS('text-align', 'center'); await expect(test).toHaveCSS('font-size', '146px'); await expect(test).toHaveText('Hello Builder!'); await expect(page.evaluate(`window.b`)).resolves.toBe(2); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.html'))!]; expect( content.includes('.test{font-size:146px;background-color:green}'), ).toBeTruthy(); expect( content.includes('#a{text-align:center;line-height:1.5;font-size:1.5rem}'), ).toBeTruthy(); expect(content.includes('window.a=1,window.b=2')).toBeTruthy(); builder.close(); });
569
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html/minify/index.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; const fixtures = __dirname; test('should minify template js & css', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, runServer: true, builderConfig: { html: { template: './static/index.html', }, performance: { removeConsole: ['log', 'warn'], }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const test = page.locator('#test'); await expect(test).toHaveCSS('text-align', 'center'); await expect(test).toHaveCSS('font-size', '146px'); await expect(test).toHaveText('Hello Builder!'); await expect(page.evaluate(`window.b`)).resolves.toBe(2); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.html'))!]; expect( content.includes('.test{font-size:146px;background-color:green}'), ).toBeTruthy(); expect( content.includes('#a{text-align:center;line-height:1.5;font-size:1.5rem}'), ).toBeTruthy(); expect(content.includes('window.a=1,window.b=2')).toBeTruthy(); expect(content.includes('console.info(111111)')).toBeTruthy(); expect(content.includes('console.warn(111111)')).toBeFalsy(); // keep html comments expect(content.includes('<!-- HTML COMMENT-->')).toBeTruthy(); builder.close(); }); webpackOnlyTest( 'should minify template success when enableInlineScripts & enableInlineStyles', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, runServer: true, builderConfig: { html: { template: './static/index.html', // avoid Minified React error #200; inject: 'body', }, output: { enableInlineScripts: true, enableInlineStyles: true, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const test = page.locator('#test'); await expect(test).toHaveCSS('text-align', 'center'); await expect(test).toHaveCSS('font-size', '146px'); await expect(test).toHaveText('Hello Builder!'); await expect(page.evaluate(`window.b`)).resolves.toBe(2); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.html'))!]; expect( content.includes('.test{font-size:146px;background-color:green}'), ).toBeTruthy(); expect(content.includes('window.a=1,window.b=2')).toBeTruthy(); builder.close(); }, );
578
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/html/script-loading/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should apply defer by default', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; expect(html).toContain('<script defer="defer" src="'); }); test('should remove defer when scriptLoading is "blocking"', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { html: { scriptLoading: 'blocking', }, }, }); const files = await builder.unwrapOutputJSON(); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; expect(html).toContain('<script src="'); }); test('should allow to set scriptLoading to "module"', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { html: { scriptLoading: 'module', }, }, }); const files = await builder.unwrapOutputJSON(); const html = files[Object.keys(files).find(file => file.endsWith('index.html'))!]; expect(html).toContain('<script type="module" src="'); });
586
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/ignore-css/removeCss.test.ts
import path from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should ignore css content when build node target', async () => { const builder = await build({ cwd: __dirname, target: 'node', entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.js'))!]; // preserve css modules mapping expect(content.includes('"title-class":')).toBeTruthy(); // remove css content expect(content.includes('.title-class')).toBeFalsy(); expect(content.includes('.header-class')).toBeFalsy(); }); test('should ignore css content when build web-worker target', async () => { const builder = await build({ cwd: __dirname, target: 'web-worker', entry: { index: path.resolve(__dirname, './src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.js'))!]; // preserve css modules mapping expect(content.includes('"title-class":')).toBeTruthy(); // remove css content expect(content.includes('.title-class')).toBeFalsy(); expect(content.includes('.header-class')).toBeFalsy(); });
591
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/image-compress/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { builderPluginImageCompress } from '@modern-js/builder-plugin-image-compress'; import { providerType } from '@scripts/helper'; import { build } from '@scripts/shared'; import { SharedBuilderPluginAPI } from '@modern-js/builder-shared'; test('should compress image with use builder-plugin-image-compress', async () => { let assets: any[]; await expect( build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, plugins: [ builderPluginImageCompress(), { name: 'builder-plugin-file-size', setup(api: SharedBuilderPluginAPI) { api.onAfterBuild(async ({ stats }) => { const res = stats?.toJson({ all: false, assets: true, }); const allAssets = res?.assets || // @ts-expect-error res?.children.reduce( (prev: any[], curr: any) => prev.concat(curr.assets || []), [], ); assets = allAssets?.filter((a: any) => ['.png', '.jpeg', '.ico'].includes(path.extname(a.name)), ); }); }, }, ], }), ).resolves.toBeDefined(); expect( assets!.find(a => path.extname(a.name) === '.png').size, ).toBeLessThanOrEqual(46126); if (providerType !== 'rspack') { // TODO: rspack stats structure is inconsistent with webpack v5, but it does not affect the use assets!.forEach(a => { expect(a.info.minimized).toBeTruthy(); }); } });
594
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/import-antd-v4/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test.setTimeout(120000); test('should import antd v4 correctly', async () => { const builder = await build( { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts') }, }, undefined, false, ); const files = await builder.unwrapOutputJSON(); expect( Object.keys(files).find(file => file.includes('lib-antd')), ).toBeTruthy(); });
598
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/import-antd-v5/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test.setTimeout(120000); test('should import antd v5 correctly', async () => { const builder = await build( { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts') }, }, undefined, false, ); const files = await builder.unwrapOutputJSON(); expect( Object.keys(files).find(file => file.includes('lib-antd')), ).toBeTruthy(); });
602
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/import-arco/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should import arco correctly', async () => { const builder = await build( { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts') }, }, undefined, false, ); const files = await builder.unwrapOutputJSON(); expect( Object.keys(files).find( file => file.includes('lib-arco') && file.includes('.js'), ), ).toBeTruthy(); expect( Object.keys(files).find( file => file.includes('lib-arco') && file.includes('.css'), ), ).toBeTruthy(); });
606
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/inline-chunk/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { webpackOnlyTest } from '@scripts/helper'; import { build, getHrefByEntryName } from '@scripts/shared'; import { BundlerChain, RUNTIME_CHUNK_NAME } from '@modern-js/builder-shared'; // Rspack will not output builder runtime source map, but it not necessary // Identify whether the builder runtime chunk is included through some specific code snippets const isRuntimeChunkInHtml = (html: string): boolean => Boolean(html.includes('builder-runtime') && html.includes('Loading chunk')); // use source-map for easy to test. By default, builder use hidden-source-map const toolsConfig = { bundlerChain: (chain: BundlerChain) => { chain.devtool('source-map'); }, htmlPlugin: (config: any) => { // minify will remove sourcemap comment if (typeof config.minify === 'object') { config.minify.minifyJS = false; config.minify.minifyCSS = false; } }, }; test.describe('disableInlineRuntimeChunk', () => { let builder: Awaited<ReturnType<typeof build>>; let files: Record<string, string>; test.beforeAll(async () => { builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, runServer: true, builderConfig: { tools: toolsConfig, output: { disableInlineRuntimeChunk: true, }, }, }); files = await builder.unwrapOutputJSON(false); }); test.afterAll(async () => { builder.close(); }); test('should emit builder runtime', async ({ page }) => { // test runtime await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate(`window.test`)).toBe('aaaa'); // builder-runtime file in output expect( Object.keys(files).some( fileName => fileName.includes(RUNTIME_CHUNK_NAME) && fileName.endsWith('.js'), ), ).toBe(true); }); }); test('inline runtime chunk by default', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, runServer: true, builderConfig: { tools: toolsConfig, }, }); // test runtime await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate(`window.test`)).toBe('aaaa'); const files = await builder.unwrapOutputJSON(false); // no builder-runtime file in output expect( Object.keys(files).some( fileName => fileName.includes(RUNTIME_CHUNK_NAME) && fileName.endsWith('.js'), ), ).toBe(false); // found builder-runtime file in html const indexHtml = files[path.resolve(__dirname, './dist/html/index/index.html')]; expect(isRuntimeChunkInHtml(indexHtml)).toBeTruthy(); builder.close(); }); test('inline runtime chunk and remove source map when devtool is "hidden-source-map"', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { tools: { bundlerChain(chain) { chain.devtool('hidden-source-map'); }, }, }, }); const files = await builder.unwrapOutputJSON(false); // should not emit source map of builder runtime expect( Object.keys(files).some( fileName => fileName.includes(RUNTIME_CHUNK_NAME) && fileName.endsWith('.js.map'), ), ).toBe(false); }); test('inline runtime chunk by default with multiple entries', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), another: path.resolve(__dirname, './src/another.js'), }, builderConfig: { tools: toolsConfig, }, }); const files = await builder.unwrapOutputJSON(false); // no builder-runtime file in output expect( Object.keys(files).some( fileName => fileName.includes(RUNTIME_CHUNK_NAME) && fileName.endsWith('.js'), ), ).toBe(false); // found builder-runtime file in html const indexHtml = files[path.resolve(__dirname, './dist/html/index/index.html')]; const anotherHtml = files[path.resolve(__dirname, './dist/html/another/index.html')]; expect(isRuntimeChunkInHtml(indexHtml)).toBeTruthy(); expect(isRuntimeChunkInHtml(anotherHtml)).toBeTruthy(); }); webpackOnlyTest( 'inline all scripts should work and emit all source maps', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), another: path.resolve(__dirname, './src/another.js'), }, runServer: true, builderConfig: { output: { enableInlineScripts: true, }, tools: toolsConfig, }, }); await page.goto(getHrefByEntryName('index', builder.port)); // test runtime expect(await page.evaluate(`window.test`)).toBe('aaaa'); const files = await builder.unwrapOutputJSON(false); // no entry chunks or runtime chunks in output expect( Object.keys(files).filter( fileName => fileName.endsWith('.js') && !fileName.includes('/async/'), ).length, ).toEqual(0); // all source maps in output expect( Object.keys(files).filter(fileName => fileName.endsWith('.js.map')) .length, ).toEqual(4); builder.close(); }, ); test('using RegExp to inline scripts', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, builderConfig: { output: { enableInlineScripts: /\/index\.\w+\.js$/, }, tools: toolsConfig, }, }); const files = await builder.unwrapOutputJSON(false); // no index.js in output expect( Object.keys(files).filter( fileName => fileName.endsWith('.js') && fileName.includes('/index.'), ).length, ).toEqual(0); // all source maps in output expect( Object.keys(files).filter(fileName => fileName.endsWith('.js.map')).length, ).toBeGreaterThanOrEqual(2); }); test('inline scripts by filename and file size', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, builderConfig: { output: { enableInlineScripts({ size, name }) { return name.includes('index') && size < 1000; }, }, tools: toolsConfig, }, }); const files = await builder.unwrapOutputJSON(false); // no index.js in output expect( Object.keys(files).filter( fileName => fileName.endsWith('.js') && fileName.includes('/index.'), ).length, ).toEqual(0); // all source maps in output expect( Object.keys(files).filter(fileName => fileName.endsWith('.js.map')).length, ).toBeGreaterThanOrEqual(2); }); test('using RegExp to inline styles', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, builderConfig: { output: { enableInlineStyles: /\/index\.\w+\.css$/, }, tools: toolsConfig, }, }); const files = await builder.unwrapOutputJSON(false); // no index.css in output expect( Object.keys(files).filter( fileName => fileName.endsWith('.css') && fileName.includes('/index.'), ).length, ).toEqual(0); }); test('inline styles by filename and file size', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, builderConfig: { output: { enableInlineStyles({ size, name }) { return name.includes('index') && size < 1000; }, }, tools: toolsConfig, }, }); const files = await builder.unwrapOutputJSON(false); // no index.css in output expect( Object.keys(files).filter( fileName => fileName.endsWith('.css') && fileName.includes('/index.'), ).length, ).toEqual(0); });
611
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/inspect-config/index.test.ts
import path from 'path'; import { fs } from '@modern-js/utils'; import { expect, test } from '@modern-js/e2e/playwright'; import { createBuilder } from '@scripts/shared'; const builderConfig = path.resolve(__dirname, './dist/builder.config.js'); const bundlerConfig = path.resolve( __dirname, `./dist/${process.env.PROVIDE_TYPE || 'webpack'}.config.web.js`, ); const bundlerNodeConfig = path.resolve( __dirname, `./dist/${process.env.PROVIDE_TYPE || 'webpack'}.config.node.js`, ); test('should generate config files when writeToDisk is true', async () => { const builder = await createBuilder( { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, }, {}, ); await builder.inspectConfig({ writeToDisk: true, }); expect(fs.existsSync(bundlerConfig)).toBeTruthy(); expect(fs.existsSync(builderConfig)).toBeTruthy(); fs.removeSync(builderConfig); fs.removeSync(bundlerConfig); }); test('should generate bundler config for node when target contains node', async () => { const builder = await createBuilder( { cwd: __dirname, target: ['web', 'node'], entry: { index: path.resolve(__dirname, './src/index.js'), }, }, {}, ); await builder.inspectConfig({ writeToDisk: true, }); expect(fs.existsSync(builderConfig)).toBeTruthy(); expect(fs.existsSync(bundlerConfig)).toBeTruthy(); expect(fs.existsSync(bundlerNodeConfig)).toBeTruthy(); fs.removeSync(builderConfig); fs.removeSync(bundlerConfig); fs.removeSync(bundlerNodeConfig); }); test('should not generate config files when writeToDisk is false', async () => { const builder = await createBuilder( { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, }, {}, ); await builder.inspectConfig({ writeToDisk: false, }); expect(fs.existsSync(builderConfig)).toBeFalsy(); expect(fs.existsSync(bundlerConfig)).toBeFalsy(); });
613
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/legalComments/index.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = __dirname; test('legalComments linked (default)', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.jsx'), }, runServer: true, builderConfig: { performance: { chunkSplit: { strategy: 'all-in-one', }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.innerHTML('#test')).resolves.toBe('Hello Builder!'); const files = await builder.unwrapOutputJSON(); const LicenseContent = files[ Object.keys(files).find( file => file.includes('js/main') && file.endsWith('.LICENSE.txt'), )! ]; expect(LicenseContent.includes('@preserve AAAA')).toBeTruthy(); expect(LicenseContent.includes('@license BBB')).toBeTruthy(); expect(LicenseContent.includes('Legal Comment CCC')).toBeTruthy(); expect(LicenseContent.includes('Foo Bar')).toBeFalsy(); const JsContent = files[ Object.keys(files).find( file => file.includes('js/main') && file.endsWith('.js'), )! ]; expect(JsContent.includes('Foo Bar')).toBeFalsy(); builder.close(); }); test('legalComments none', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.jsx'), }, runServer: true, builderConfig: { performance: { chunkSplit: { strategy: 'all-in-one', }, }, output: { legalComments: 'none', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.innerHTML('#test')).resolves.toBe('Hello Builder!'); const files = await builder.unwrapOutputJSON(); const LicenseFile = Object.keys(files).find( file => file.includes('js/main') && file.endsWith('.LICENSE.txt'), )!; expect(LicenseFile).toBeUndefined(); const JsContent = files[ Object.keys(files).find( file => file.includes('js/main') && file.endsWith('.js'), )! ]; expect(JsContent.includes('@license BBB')).toBeFalsy(); builder.close(); }); test('legalComments inline', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.jsx'), }, runServer: true, builderConfig: { performance: { chunkSplit: { strategy: 'all-in-one', }, }, output: { legalComments: 'inline', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.innerHTML('#test')).resolves.toBe('Hello Builder!'); const files = await builder.unwrapOutputJSON(); const LicenseFile = Object.keys(files).find( file => file.includes('js/main') && file.endsWith('.LICENSE.txt'), )!; expect(LicenseFile).toBeUndefined(); const JsContent = files[ Object.keys(files).find( file => file.includes('js/main') && file.endsWith('.js'), )! ]; expect(JsContent.includes('@license BBB')).toBeTruthy(); expect(JsContent.includes('Foo Bar')).toBeFalsy(); builder.close(); });
615
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/lodash/index.swc.test.ts
import * as path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { builderPluginSwc } from '@modern-js/builder-plugin-swc'; test('should optimize lodash bundle size when using SWC plugin', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts'), }, builderConfig: { performance: { chunkSplit: { strategy: 'all-in-one', }, }, output: { distPath: { root: 'dist-swc', }, }, }, plugins: [builderPluginSwc()], runServer: false, }); const { content, size } = await builder.getIndexFile(); expect(content.includes('debounce')).toBeFalsy(); expect(size < 10).toBeTruthy(); }); test('should not optimize lodash bundle size when transformLodash is false and using SWC plugin', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts'), }, builderConfig: { performance: { transformLodash: false, chunkSplit: { strategy: 'all-in-one', }, }, output: { distPath: { root: 'dist-swc', }, }, }, plugins: [builderPluginSwc()], runServer: false, }); const { content, size } = await builder.getIndexFile(); expect(content.includes('debounce')).toBeTruthy(); expect(size > 30).toBeTruthy(); });
616
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/lodash/index.test.ts
import * as path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { webpackOnlyTest } from '@scripts/helper'; import { build } from '@scripts/shared'; // TODO: needs builtin:swc-loader webpackOnlyTest('should optimize lodash bundle size by default', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts'), }, builderConfig: { performance: { chunkSplit: { strategy: 'all-in-one', }, }, }, runServer: false, }); const { content, size } = await builder.getIndexFile(); expect(content.includes('debounce')).toBeFalsy(); expect(size < 10).toBeTruthy(); }); test('should not optimize lodash bundle size when transformLodash is false', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts'), }, builderConfig: { performance: { transformLodash: false, chunkSplit: { strategy: 'all-in-one', }, }, }, runServer: false, }); const { content, size } = await builder.getIndexFile(); expect(content.includes('debounce')).toBeTruthy(); expect(size > 30).toBeTruthy(); });
618
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/manifest/index.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; const fixtures = __dirname; test('enableAssetManifest', async () => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.jsx'), }, builderConfig: { output: { enableAssetManifest: true, legalComments: 'none', }, performance: { chunkSplit: { strategy: 'all-in-one', }, }, }, }); const files = await builder.unwrapOutputJSON(); const manifestContent = files[ Object.keys(files).find(file => file.endsWith('asset-manifest.json'))! ]; expect(manifestContent).toBeDefined(); const manifest = JSON.parse(manifestContent); // main.js、index.html、main.js.map expect(Object.keys(manifest.files).length).toBe(3); expect(manifest.entrypoints.length).toBe(1); builder.close(); });
620
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/moment/index.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; // todo: https://github.com/web-infra-dev/rspack/issues/3346 webpackOnlyTest('removeMomentLocale false (default)', async () => { const builder = await build({ cwd: __dirname, entry: { main: join(__dirname, './src/index.js') }, builderConfig: { performance: { chunkSplit: { strategy: 'custom', splitChunks: { cacheGroups: { react: { test: /moment/, name: 'moment-js', chunks: 'all', }, }, }, }, }, }, runServer: false, }); const files = await builder.unwrapOutputJSON(false); const fileName = Object.keys(files).find( file => file.includes('moment-js') && file.endsWith('.js.map'), ); const momentMapFile = files[fileName!]; expect(momentMapFile.includes('moment/locale')).toBeTruthy(); }); test('removeMomentLocale true', async () => { const builder = await build({ cwd: __dirname, entry: { main: join(__dirname, './src/index.js') }, builderConfig: { performance: { removeMomentLocale: true, chunkSplit: { strategy: 'custom', splitChunks: { cacheGroups: { react: { test: /moment/, name: 'moment-js', chunks: 'all', }, }, }, }, }, }, runServer: false, }); const files = await builder.unwrapOutputJSON(false); const fileName = Object.keys(files).find( file => file.includes('moment-js') && file.endsWith('.js.map'), ); const momentMapFile = files[fileName!]; expect(momentMapFile.includes('moment/locale')).toBeFalsy(); });
623
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/node-addons/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should compile Node addons correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, target: 'node', }); const files = await builder.unwrapOutputJSON(); const addonFile = Object.keys(files).find(file => file.endsWith('a.node')); expect(addonFile?.includes('bundles/a.node')).toBeTruthy(); });
625
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/node-polyfill/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { builderPluginNodePolyfill } from '@modern-js/builder-plugin-node-polyfill'; test('should add node-polyfill when add node-polyfill plugin', async ({ page, }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, plugins: [builderPluginNodePolyfill()], runServer: true, }); await page.goto(getHrefByEntryName('index', builder.port)); const test = page.locator('#test'); await expect(test).toHaveText('Hello Builder!'); const testBuffer = page.locator('#test-buffer'); await expect(testBuffer).toHaveText('120120120120'); const testQueryString = page.locator('#test-querystring'); await expect(testQueryString).toHaveText('foo=bar'); builder.close(); });
628
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output/assets.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = __dirname; const cases = [ { name: 'assets(default)', cwd: join(fixtures, 'assets'), expected: 'inline', }, { name: 'assets(maxSize 0)', cwd: join(fixtures, 'assets'), config: { output: { dataUriLimit: { image: 0, }, }, }, expected: 'url', }, { name: 'assets(maxSize Infinity)', cwd: join(fixtures, 'assets'), config: { output: { dataUriLimit: { // Rspack not support Infinity image: 5 * 1024, }, }, }, expected: 'inline', }, { name: 'assets-url', cwd: join(fixtures, 'assets-url'), expected: 'url', }, { name: 'assets-no-inline', cwd: join(fixtures, 'assets-no-inline'), expected: 'url', }, { name: 'assets__inline', cwd: join(fixtures, 'assets__inline'), expected: 'inline', }, { name: 'assets-inline', cwd: join(fixtures, 'assets-inline'), expected: 'inline', }, ]; cases.forEach(_case => { test(_case.name, async ({ page }) => { const builder = await build({ cwd: _case.cwd, entry: { main: join(_case.cwd, 'src/index.js'), }, runServer: true, builderConfig: _case.config || {}, }); await page.goto(getHrefByEntryName('main', builder.port)); if (_case.expected === 'url') { await expect( page.evaluate( `document.getElementById('test-img').src.includes('static/image/icon')`, ), ).resolves.toBeTruthy(); } else { await expect( page.evaluate( `document.getElementById('test-img').src.startsWith('data:image/png')`, ), ).resolves.toBeTruthy(); } builder.close(); }); });
629
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output/output.test.ts
import { join, dirname } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { fs } from '@modern-js/utils'; import { build } from '@scripts/shared'; const fixtures = __dirname; test.describe('output configure multi', () => { const distFilePath = join(fixtures, 'rem/dist-1/test.json'); let builder: Awaited<ReturnType<typeof build>>; test.beforeAll(async () => { await fs.mkdir(dirname(distFilePath), { recursive: true }); await fs.writeFile( distFilePath, `{ "test": 1 }`, ); builder = await build({ cwd: join(fixtures, 'rem'), entry: { main: join(fixtures, 'rem/src/index.ts'), }, builderConfig: { output: { distPath: { root: 'dist-1', js: 'aa/js', }, copy: [{ from: './src/assets', to: '' }], }, }, }); }); test.afterAll(async () => { builder.close(); await builder.clean(); }); test('cleanDistPath default (enable)', async () => { expect(fs.existsSync(distFilePath)).toBeFalsy(); }); test('copy', async () => { expect(fs.existsSync(join(fixtures, 'rem/dist-1/icon.png'))).toBeTruthy(); }); test('distPath', async () => { expect( fs.existsSync(join(fixtures, 'rem/dist-1/html/main/index.html')), ).toBeTruthy(); expect(fs.existsSync(join(fixtures, 'rem/dist-1/aa/js'))).toBeTruthy(); }); test('sourcemap', async () => { const files = await builder.unwrapOutputJSON(false); const jsMapFiles = Object.keys(files).filter(files => files.endsWith('.js.map'), ); const cssMapFiles = Object.keys(files).filter(files => files.endsWith('.css.map'), ); expect(jsMapFiles.length).toBeGreaterThanOrEqual(1); expect(cssMapFiles.length).toBe(0); }); }); test('cleanDistPath disable', async () => { const distFilePath = join(fixtures, 'rem/dist-2/test.json'); await fs.mkdir(dirname(distFilePath), { recursive: true }); await fs.writeFile( distFilePath, `{ "test": 1 }`, ); const builder = await build({ cwd: join(fixtures, 'rem'), entry: { main: join(fixtures, 'rem/src/index.ts'), }, builderConfig: { output: { distPath: { root: 'dist-2', }, cleanDistPath: false, }, }, }); expect(fs.existsSync(distFilePath)).toBeTruthy(); builder.close(); builder.clean(); }); test('disableSourcemap', async () => { const builder = await build({ cwd: join(fixtures, 'rem'), entry: { main: join(fixtures, 'rem/src/index.ts'), }, builderConfig: { output: { distPath: { root: 'dist-3', }, disableSourceMap: true, }, }, }); const files = await builder.unwrapOutputJSON(false); const jsMapFiles = Object.keys(files).filter(files => files.endsWith('.js.map'), ); const cssMapFiles = Object.keys(files).filter(files => files.endsWith('.css.map'), ); expect(jsMapFiles.length).toBe(0); expect(cssMapFiles.length).toBe(0); });
630
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output/ascii/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; test('output.charset default (ascii)', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, runServer: true, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.a')).toBe('你好 world!'); const files = await builder.unwrapOutputJSON(); const [, content] = Object.entries(files).find( ([name]) => name.endsWith('.js') && name.includes('static/js/index'), )!; // in rspack is: \\u4f60\\u597D world! expect( content.toLocaleLowerCase().includes('\\u4f60\\u597d world!'), ).toBeTruthy(); builder.close(); }); test('output.charset (utf8)', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js'), }, builderConfig: { output: { charset: 'utf8', }, }, runServer: true, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.a')).toBe('你好 world!'); const files = await builder.unwrapOutputJSON(); const [, content] = Object.entries(files).find( ([name]) => name.endsWith('.js') && name.includes('static/js/index'), )!; expect(content.includes('你好 world!')).toBeTruthy(); builder.close(); });
636
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output/assets-retry/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should inline assets retry runtime code to html by default', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { output: { assetsRetry: {}, }, tools: { htmlPlugin: (config: any) => { // minifyJS will minify function name if (typeof config.minify === 'object') { config.minify.minifyJS = false; config.minify.minifyCSS = false; } }, }, }, }); const files = await builder.unwrapOutputJSON(); const htmlFile = Object.keys(files).find(file => file.endsWith('.html')); expect(htmlFile).toBeTruthy(); expect(files[htmlFile!].includes('function retry')).toBeTruthy(); }); test('should extract assets retry runtime code when inlineScript is false', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { output: { assetsRetry: { inlineScript: false, }, }, }, }); const files = await builder.unwrapOutputJSON(); const htmlFile = Object.keys(files).find(file => file.endsWith('.html')); const retryFile = Object.keys(files).find( file => file.includes('/assets-retry') && file.endsWith('.js'), ); expect(htmlFile).toBeTruthy(); expect(retryFile).toBeTruthy(); expect(files[htmlFile!].includes('function retry')).toBeFalsy(); });
648
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output/externals
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output/externals/tests/index.test.ts
import { join, resolve } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = resolve(__dirname, '../'); test('externals', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.js'), }, runServer: true, builderConfig: { output: { externals: { './aaa': 'aa', }, }, source: { preEntry: './src/ex.js', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const test = page.locator('#test'); await expect(test).toHaveText('Hello Builder!'); const testExternal = page.locator('#test-external'); await expect(testExternal).toHaveText('1'); const externalVar = await page.evaluate(`window.aa`); expect(externalVar).toBeDefined(); builder.clean(); builder.close(); }); test('should not external dependencies when target is web worker', async () => { const builder = await build({ cwd: fixtures, target: 'web-worker', entry: { index: resolve(fixtures, './src/index.js') }, builderConfig: { output: { externals: { react: 'MyReact', }, }, }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.js'))!]; expect(content.includes('MyReact')).toBeFalsy(); builder.clean(); });
656
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output/rem
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/output/rem/tests/index.test.ts
import { join, resolve } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = resolve(__dirname, '../'); test('rem default (disable)', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, runServer: true, }); await page.goto(getHrefByEntryName('main', builder.port)); const title = page.locator('#title'); await expect(title).toHaveCSS('font-size', '20px'); const description = page.locator('#description'); await expect(description).toHaveCSS('font-size', '16px'); builder.close(); }); test('rem enable', async ({ page }) => { // convert to rem const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, runServer: true, builderConfig: { output: { convertToRem: true, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const root = page.locator('html'); await expect(root).toHaveCSS('font-size', '64px'); // less convert pxToRem const title = page.locator('#title'); await expect(title).toHaveCSS('font-size', '25.6px'); // scss convert pxToRem const header = page.locator('#header'); await expect(header).toHaveCSS('font-size', '25.6px'); // css convert pxToRem const description = page.locator('#description'); await expect(description).toHaveCSS('font-size', '20.48px'); builder.close(); }); test('should inline runtime code to html by default', async () => { const builder = await build({ cwd: fixtures, entry: { index: join(fixtures, 'src/index.ts') }, builderConfig: { output: { convertToRem: {}, }, }, }); const files = await builder.unwrapOutputJSON(); const htmlFile = Object.keys(files).find(file => file.endsWith('.html')); expect(htmlFile).toBeTruthy(); expect(files[htmlFile!].includes('function setRootPixel')).toBeTruthy(); }); test('should extract runtime code when inlineRuntime is false', async () => { const builder = await build({ cwd: fixtures, entry: { index: join(fixtures, 'src/index.ts') }, builderConfig: { output: { convertToRem: { inlineRuntime: false, }, }, }, }); const files = await builder.unwrapOutputJSON(); const htmlFile = Object.keys(files).find(file => file.endsWith('.html')); const retryFile = Object.keys(files).find( file => file.includes('/convert-rem') && file.endsWith('.js'), ); expect(htmlFile).toBeTruthy(); expect(retryFile).toBeTruthy(); expect(files[htmlFile!].includes('function setRootPixel')).toBeFalsy(); });
657
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/performance/performance.test.ts
import { join, resolve } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; const fixtures = __dirname; test.describe('performance configure multi', () => { let files: Record<string, string>; const basicFixtures = resolve(__dirname, 'basic'); test.beforeAll(async () => { const builder = await build({ cwd: basicFixtures, entry: { main: join(basicFixtures, 'src/index.ts'), }, builderConfig: { performance: { bundleAnalyze: {}, chunkSplit: { strategy: 'all-in-one', }, }, }, }); files = await builder.unwrapOutputJSON(); }); test('bundleAnalyze', async () => { const filePaths = Object.keys(files).filter(file => file.endsWith('report-web.html'), ); expect(filePaths.length).toBe(1); }); test('chunkSplit all-in-one', async () => { // expect only one bundle (end with .js) const filePaths = Object.keys(files).filter(file => file.endsWith('.js')); expect(filePaths.length).toBe(1); }); }); test('should generate vendor chunk when chunkSplit is "single-vendor"', async () => { const builder = await build({ cwd: join(fixtures, 'basic'), entry: { main: join(fixtures, 'basic/src/index.ts'), }, builderConfig: { performance: { chunkSplit: { strategy: 'single-vendor', }, }, }, }); const files = await builder.unwrapOutputJSON(); const [vendorFile] = Object.entries(files).find( ([name, content]) => name.includes('vendor') && content.includes('React'), )!; expect(vendorFile).toBeTruthy(); }); test('should generate preconnect link when preconnect is defined', async () => { const builder = await build({ cwd: join(fixtures, 'basic'), entry: { main: join(fixtures, 'basic/src/index.ts'), }, builderConfig: { performance: { preconnect: [ { href: 'http://aaaa.com', }, { href: 'http://bbbb.com', crossorigin: true, }, ], }, }, }); const files = await builder.unwrapOutputJSON(); const [, content] = Object.entries(files).find(([name]) => name.endsWith('index.html'), )!; expect( content.includes('<link rel="preconnect" href="http://aaaa.com">'), ).toBeTruthy(); expect( content.includes( '<link rel="preconnect" href="http://bbbb.com" crossorigin>', ), ).toBeTruthy(); }); test('should generate dnsPrefetch link when dnsPrefetch is defined', async () => { const builder = await build({ cwd: join(fixtures, 'basic'), entry: { main: join(fixtures, 'basic/src/index.ts'), }, builderConfig: { performance: { dnsPrefetch: ['http://aaaa.com'], }, }, }); const files = await builder.unwrapOutputJSON(); const [, content] = Object.entries(files).find(([name]) => name.endsWith('index.html'), )!; expect( content.includes('<link rel="dns-prefetch" href="http://aaaa.com">'), ).toBeTruthy(); });
658
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/performance/removeConsole.swc.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { builderPluginSwc } from '@modern-js/builder-plugin-swc'; const cwd = join(__dirname, 'removeConsole'); const expectConsoleType = async ( builder: Awaited<ReturnType<typeof build>>, consoleType: Record<string, boolean>, ) => { const files = await builder.unwrapOutputJSON(); const mainFile = Object.keys(files).find( name => name.includes('main.') && name.endsWith('.js'), )!; const content = files[mainFile]; Object.entries(consoleType).forEach(([key, value]) => { expect(content.includes(`test-console-${key}`)).toEqual(value); }); }; test('should remove specified console correctly when using SWC plugin', async () => { const builder = await build({ cwd, entry: { main: join(cwd, 'src/index.js'), }, plugins: [builderPluginSwc()], builderConfig: { performance: { removeConsole: ['log', 'warn'], }, }, }); await expectConsoleType(builder, { log: false, warn: false, debug: true, error: true, }); }); test('should remove all console correctly when using SWC plugin', async () => { const builder = await build({ cwd, entry: { main: join(cwd, 'src/index.js'), }, plugins: [builderPluginSwc()], builderConfig: { performance: { removeConsole: true, }, }, }); await expectConsoleType(builder, { log: false, warn: false, debug: false, error: false, }); });
659
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/performance/removeConsole.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; const cwd = join(__dirname, 'removeConsole'); const expectConsoleType = async ( builder: Awaited<ReturnType<typeof build>>, consoleType: Record<string, boolean>, ) => { const files = await builder.unwrapOutputJSON(); const mainFile = Object.keys(files).find( name => name.includes('main.') && name.endsWith('.js'), )!; const content = files[mainFile]; Object.entries(consoleType).forEach(([key, value]) => { expect(content.includes(`test-console-${key}`)).toEqual(value); }); }; test('should remove specified console correctly', async () => { const builder = await build({ cwd, entry: { main: join(cwd, 'src/index.js'), }, builderConfig: { performance: { removeConsole: ['log', 'warn'], }, }, }); await expectConsoleType(builder, { log: false, warn: false, debug: true, error: true, }); }); test('should remove all console correctly', async () => { const builder = await build({ cwd, entry: { main: join(cwd, 'src/index.js'), }, builderConfig: { performance: { removeConsole: true, }, }, }); await expectConsoleType(builder, { log: false, warn: false, debug: false, error: false, }); });
663
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/performance
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/performance/load-resource/index.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; const fixtures = __dirname; test('should generate prefetch link when prefetch is defined', async () => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/page1/index.ts'), }, builderConfig: { output: { assetPrefix: 'https://www.foo.com', }, performance: { prefetch: true, }, }, }); const files = await builder.unwrapOutputJSON(); const asyncFileName = Object.keys(files).find(file => file.includes('/static/js/async/'), )!; const [, content] = Object.entries(files).find(([name]) => name.endsWith('index.html'), )!; // test.js、test.css、test.png expect(content.match(/rel="prefetch"/g)?.length).toBe(3); expect( content.includes( `<link href="https://www.foo.com${asyncFileName.slice( asyncFileName.indexOf('/static/js/async/'), )}" rel="prefetch">`, ), ).toBeTruthy(); }); test('should generate prefetch link correctly when assetPrefix do not have a protocol', async () => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/page1/index.ts'), }, builderConfig: { output: { assetPrefix: '//www.foo.com', }, performance: { prefetch: true, }, }, }); const files = await builder.unwrapOutputJSON(); const asyncFileName = Object.keys(files).find(file => file.includes('/static/js/async/'), )!; const [, content] = Object.entries(files).find(([name]) => name.endsWith('index.html'), )!; expect( content.includes( `<link href="//www.foo.com${asyncFileName.slice( asyncFileName.indexOf('/static/js/async/'), )}" rel="prefetch">`, ), ).toBeTruthy(); }); test('should generate prefetch link with filter', async () => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/page1/index.ts'), }, builderConfig: { performance: { prefetch: { include: [/.*\.png$/], }, }, }, }); const files = await builder.unwrapOutputJSON(); const asyncFileName = Object.keys(files).find(file => file.includes('/static/image/test'), )!; const [, content] = Object.entries(files).find(([name]) => name.endsWith('index.html'), )!; // test.js、test.css、test.png expect(content.match(/rel="prefetch"/g)?.length).toBe(1); expect( content.includes( `<link href="${asyncFileName.slice( asyncFileName.indexOf('/static/image/test'), )}" rel="prefetch">`, ), ).toBeTruthy(); }); webpackOnlyTest( 'should generate prefetch link by config (distinguish html)', async () => { const builder = await build({ cwd: fixtures, entry: { page1: join(fixtures, 'src/page1/index.ts'), page2: join(fixtures, 'src/page2/index.ts'), }, builderConfig: { performance: { prefetch: { type: 'all-chunks', }, }, }, }); const files = await builder.unwrapOutputJSON(); const [, content] = Object.entries(files).find(([name]) => name.endsWith('page1/index.html'), )!; // icon.png、test.js、test.css、test.png expect(content.match(/rel="prefetch"/g)?.length).toBe(4); const assetFileName = Object.keys(files).find(file => file.includes('/static/image/'), )!; expect( content.includes( `<link href="${assetFileName.slice( assetFileName.indexOf('/static/image/'), )}" rel="prefetch">`, ), ).toBeTruthy(); const [, content2] = Object.entries(files).find(([name]) => name.endsWith('page2/index.html'), )!; // test.js、test.css、test.png expect(content2.match(/rel="prefetch"/g)?.length).toBe(3); }, ); test('should generate preload link when preload is defined', async () => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/page1/index.ts'), }, builderConfig: { performance: { preload: true, }, }, }); const files = await builder.unwrapOutputJSON(); const asyncFileName = Object.keys(files).find(file => file.includes('/static/js/async/'), )!; const [, content] = Object.entries(files).find(([name]) => name.endsWith('index.html'), )!; // test.js、test.css、test.png expect(content.match(/rel="preload"/g)?.length).toBe(3); expect( content.includes( `<link href="${asyncFileName.slice( asyncFileName.indexOf('/static/js/async/'), )}" rel="preload" as="script">`, ), ).toBeTruthy(); });
666
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/performance/load-resource
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/performance/load-resource/src/test.ts
import './test.css'; // @ts-expect-error import Png from './test.png?url'; export { Png }; export const a = '1111';
672
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/polyfill/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { webpackOnlyTest } from '@scripts/helper'; import { build, getHrefByEntryName } from '@scripts/shared'; const POLYFILL_RE = /\/lib-polyfill/; const getPolyfillContent = (files: Record<string, string>) => { const polyfillFileName = Object.keys(files).find( file => POLYFILL_RE.test(file) && file.endsWith('.js.map'), ); const indexFileName = Object.keys(files).find( file => file.includes('index') && file.endsWith('.js.map'), )!; const content = polyfillFileName ? files[polyfillFileName] : files[indexFileName]; return content; }; test('should add polyfill when set polyfill entry (default)', async ({ page, }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { output: { polyfill: 'entry', }, }, runServer: true, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.a')).toEqual([1, 2, 3, 4, 5, 6, [7, 8]]); builder.close(); const files = await builder.unwrapOutputJSON(false); const content = getPolyfillContent(files); // should polyfill all api expect(content.includes('es.array.flat.js')).toBeTruthy(); }); // TODO: needs builtin:swc-loader webpackOnlyTest( 'should add polyfill when set polyfill usage', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { output: { polyfill: 'usage', }, }, runServer: true, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.a')).toEqual([1, 2, 3, 4, 5, 6, [7, 8]]); builder.close(); const files = await builder.unwrapOutputJSON(false); const content = getPolyfillContent(files); // should only polyfill some usage api expect(content.includes('es.array.flat.js')).toBeTruthy(); expect(content.includes('String.prototype.trimEnd')).toBeFalsy(); }, );
674
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/progress/index.test.ts
import path from 'path'; import { expect } from '@modern-js/e2e/playwright'; import { webpackOnlyTest } from '@scripts/helper'; import { build } from '@scripts/shared'; import { logger } from '@modern-js/utils'; webpackOnlyTest('should emit progress log in non-TTY environment', async () => { process.stdout.isTTY = false; const { info, ready } = logger; const infoMsgs: any[] = []; const readyMsgs: any[] = []; logger.info = message => { infoMsgs.push(message); }; logger.ready = message => { readyMsgs.push(message); }; await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { dev: { progressBar: true, }, }, }); expect( infoMsgs.some(message => message.includes('Client compile progress')), ).toBeTruthy(); expect( readyMsgs.some(message => message.includes('Client compiled')), ).toBeTruthy(); process.stdout.isTTY = true; logger.info = info; logger.ready = ready; });
676
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/react
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/react/remove-prop-types/index.test.ts
import { join } from 'path'; import { expect } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; const fixtures = __dirname; // TODO: needs builtin:swc-loader webpackOnlyTest('should remove prop-types by default', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.js'), }, runServer: true, }); await page.goto(getHrefByEntryName('main', builder.port)); expect(await page.evaluate('window.testAppPropTypes')).toBeUndefined(); builder.close(); });
680
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/serve/index.test.ts
import { join } from 'path'; import { fs } from '@modern-js/utils'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; test('should serve dist files correctly', async ({ page }) => { const cwd = join(__dirname, 'basic'); const { instance } = await build({ cwd, entry: { main: join(cwd, 'src/index.js'), }, }); const { port, server } = await instance.serve(); await page.goto(getHrefByEntryName('main', port)); const rootEl = page.locator('#root'); await expect(rootEl).toHaveText('Hello Builder!'); await server.close(); await fs.remove(join(cwd, 'dist-1')); });
683
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source-map/source.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import sourceMap from 'source-map'; const fixtures = __dirname; async function validateSourceMap( rawSourceMap: string, generatedPositions: { line: number; column: number; }[], ) { const consumer = await new sourceMap.SourceMapConsumer(rawSourceMap); const originalPositions = generatedPositions.map(generatedPosition => consumer.originalPositionFor({ line: generatedPosition.line, column: generatedPosition.column, }), ); consumer.destroy(); return originalPositions; } test('source-map', async () => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.js'), }, builderConfig: { output: { legalComments: 'none', }, performance: { chunkSplit: { strategy: 'all-in-one', }, }, }, }); const files = await builder.unwrapOutputJSON(false); const [, jsMapContent] = Object.entries(files).find( ([name]) => name.includes('static/js/') && name.endsWith('.js.map'), )!; const [, jsContent] = Object.entries(files).find( ([name]) => name.includes('static/js/') && name.endsWith('.js'), )!; const AppContentIndex = jsContent.indexOf('Hello Builder!'); const indexContentIndex = jsContent.indexOf('window.aa'); const originalPositions = ( await validateSourceMap(jsMapContent, [ { line: 1, column: AppContentIndex, }, { line: 1, column: indexContentIndex, }, ]) ).map(o => ({ ...o, source: o.source!.split('webpack-builder-source-map/')[1] || o.source, })); expect(originalPositions[0]).toEqual({ source: 'src/App.jsx', line: 2, column: 24, name: null, }); expect(originalPositions[1]).toEqual({ source: 'src/index.js', line: 6, column: 0, name: 'window', }); });
686
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/source.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = __dirname; test.describe('source configure multi', () => { let builder: Awaited<ReturnType<typeof build>>; test.beforeAll(async () => { builder = await build({ cwd: join(fixtures, 'basic'), entry: { main: join(fixtures, 'basic/src/index.js'), }, runServer: true, builderConfig: { source: { alias: { '@common': './src/common', }, preEntry: ['./src/pre.js'], }, }, }); }); test.afterAll(() => { builder.close(); }); test('alias', async ({ page }) => { await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.innerHTML('#test')).resolves.toBe('Hello Builder! 1'); }); test('pre-entry', async ({ page }) => { await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.innerHTML('#test-el')).resolves.toBe('aaaaa'); // test order await expect(page.evaluate(`window.aa`)).resolves.toBe(2); }); }); // todo: moduleScopes not work when buildCache is false ??? test.skip('module-scopes', async ({ page }) => { const buildOpts = { cwd: join(fixtures, 'module-scopes'), entry: { main: join(fixtures, 'module-scopes/src/index.js'), }, }; await expect( build({ ...buildOpts, builderConfig: { source: { moduleScopes: ['./src'], }, }, }), ).rejects.toThrowError('webpack build failed!'); let builder = await build({ ...buildOpts, runServer: true, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.innerHTML('#test')).resolves.toBe('Hello Builder! 1'); builder.close(); // should not throw builder = await build({ ...buildOpts, builderConfig: { source: { moduleScopes: ['./src', './common'], }, }, }); builder.close(); }); test('global-vars', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'global-vars'), entry: { main: join(fixtures, 'global-vars/src/index.ts'), }, runServer: true, builderConfig: { source: { globalVars: { ENABLE_TEST: true, }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const testEl = page.locator('#test-el'); await expect(testEl).toHaveText('aaaaa'); builder.close(); }); test('define', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'global-vars'), entry: { main: join(fixtures, 'global-vars/src/index.ts'), }, runServer: true, builderConfig: { source: { define: { ENABLE_TEST: JSON.stringify(true), }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const testEl = page.locator('#test-el'); await expect(testEl).toHaveText('aaaaa'); builder.close(); }); test('tsconfig paths should work and override the alias config', async ({ page, }) => { const cwd = join(fixtures, 'tsconfig-paths'); const builder = await build({ cwd, entry: { main: join(cwd, 'src/index.ts'), }, runServer: true, builderConfig: { source: { alias: { '@common': './src/common2', }, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const foo = page.locator('#foo'); await expect(foo).toHaveText('tsconfig paths worked'); builder.close(); }); test('tsconfig paths should not work when aliasStrategy is "prefer-alias"', async ({ page, }) => { const cwd = join(fixtures, 'tsconfig-paths'); const builder = await build({ cwd, entry: { main: join(cwd, 'src/index.ts'), }, runServer: true, builderConfig: { source: { alias: { '@/common': './src/common2', }, aliasStrategy: 'prefer-alias', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const foo = page.locator('#foo'); await expect(foo).toHaveText('source.alias worked'); builder.close(); });
700
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/plugin-import/index.rspack.test.ts
import path from 'path'; import { build } from '@scripts/shared'; import { expect, test } from '@modern-js/e2e/playwright'; import { cases, shareTest, copyPkgToNodeModules, findEntry } from './helper'; test('should import with template config', async () => { copyPkgToNodeModules(); const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { source: { transformImport: [ { libraryName: 'foo', customName: 'foo/lib/{{ member }}', }, ], }, performance: { chunkSplit: { strategy: 'all-in-one', }, }, }, }); const files = await builder.unwrapOutputJSON(false); const entry = findEntry(files); expect(files[entry]).toContain('transformImport test succeed'); }); cases.forEach(c => { const [name, entry, config] = c; shareTest(`${name}-rspack`, entry, config); });
701
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/plugin-import/index.webpack.test.ts
import path from 'path'; import { build } from '@scripts/shared'; import { expect, test } from '@modern-js/e2e/playwright'; import { builderPluginSwc } from '@modern-js/builder-plugin-swc'; import { findEntry, copyPkgToNodeModules, cases, shareTest } from './helper'; /* webpack can receive Function type configuration */ test('should import with function customName', async () => { copyPkgToNodeModules(); const setupConfig = { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, }; { const builder = await build({ ...setupConfig, builderConfig: { source: { transformImport: [ { libraryName: 'foo', customName: (member: string) => `foo/lib/${member}`, }, ], }, }, }); const files = await builder.unwrapOutputJSON(false); const entry = findEntry(files); expect(files[entry]).toContain('transformImport test succeed'); } const builder = await build({ ...setupConfig, plugins: [builderPluginSwc()], builderConfig: { source: { transformImport: [ { libraryName: 'foo', customName: (member: string) => `foo/lib/${member}`, }, ], // @ts-expect-error rspack and webpack all support this disableDefaultEntries: true, entries: { index: './src/index.js', }, }, }, }); const files = await builder.unwrapOutputJSON(false); const entry = findEntry(files); expect(files[entry]).toContain('transformImport test succeed'); }); test('should import with template config with SWC', async () => { copyPkgToNodeModules(); const setupConfig = { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, plugins: [builderPluginSwc()], }; { const builder = await build({ ...setupConfig, builderConfig: { source: { transformImport: [ { libraryName: 'foo', customName: 'foo/lib/{{ member }}', }, ], }, }, }); const files = await builder.unwrapOutputJSON(false); const entry = findEntry(files); expect(files[entry]).toContain('transformImport test succeed'); } { const builder = await build({ ...setupConfig, builderConfig: { source: { transformImport: [ { libraryName: 'foo', customName: member => `foo/lib/${member}`, }, ], }, }, }); const files = await builder.unwrapOutputJSON(false); const entry = findEntry(files); expect(files[entry]).toContain('transformImport test succeed'); } }); cases.forEach(c => { const [name, entry, config] = c; shareTest(`${name}-webpack`, entry, config); shareTest(`${name}-webpack-swc`, entry, config, { plugins: [builderPluginSwc()], }); });
714
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/resolve-extension-prefix
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/resolve-extension-prefix/tests/index.test.ts
import { join, resolve } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = resolve(__dirname, '../'); test.setTimeout(120000); test('resolve-extension-prefix', async ({ page }) => { const buildOpts = { cwd: fixtures, entry: { main: join(fixtures, 'src/index.js'), }, runServer: true, }; // ex.js take effect when not set resolveExtensionPrefix let builder = await build(buildOpts); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.innerHTML('#test-el')).resolves.toBe('aaaaa'); builder.close(); // ex.web.js take effect when set resolveExtensionPrefix builder = await build({ ...buildOpts, builderConfig: { source: { resolveExtensionPrefix: '.web', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect(page.innerHTML('#test-el')).resolves.toBe('web'); builder.close(); });
715
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/source-exclude/index.test.ts
import path from 'path'; import { expect } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; // TODO: needs builtin:swc-loader webpackOnlyTest( 'should not compile specified file when source.exclude', async () => { await expect( build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { source: { exclude: [path.resolve(__dirname, './src/test.js')], }, security: { checkSyntax: true, }, }, }), ).rejects.toThrowError('[Syntax Checker]'); }, );
718
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/source-include/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; // TODO: needs builtin:swc-loader webpackOnlyTest( 'should not compile file which outside of project by default', async () => { await expect( build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { security: { checkSyntax: true, }, }, }), ).rejects.toThrowError('[Syntax Checker]'); }, ); test('should compile specified file when source.include', async () => { await expect( build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, builderConfig: { source: { include: [path.resolve(__dirname, '../test.js')], }, security: { checkSyntax: true, }, }, }), ).resolves.toBeDefined(); });
723
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/tsconfig-paths/src
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/tsconfig-paths/src/common/test.ts
export const content = 'tsconfig paths worked';
724
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/tsconfig-paths/src
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/source/tsconfig-paths/src/common2/test.ts
export const content = 'source.alias worked';
725
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/sri/index.test.ts
import path from 'path'; import { expect } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; webpackOnlyTest('security.sri', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, runServer: true, builderConfig: { security: { sri: true, }, }, }); const files = await builder.unwrapOutputJSON(); const htmlFileName = Object.keys(files).find(f => f.endsWith('.html'))!; const regex = /integrity=/g; const matches = files[htmlFileName].match(regex); // at least 1 js file and 1 css file expect(matches?.length).toBeGreaterThanOrEqual(2); await page.goto(getHrefByEntryName('index', builder.port)); const test = page.locator('#test'); await expect(test).toHaveText('Hello Builder!'); builder.close(); });
729
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/styled-component/index.swc.test.ts
import path from 'path'; import { build } from '@scripts/shared'; import { expect, test } from '@modern-js/e2e/playwright'; import { builderPluginSwc } from '@modern-js/builder-plugin-swc'; const commonConfig = { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/main.ts') }, builderConfig: { tools: { webpack: { externals: ['styled-components'], }, }, output: { disableMinimize: true, // avoid unwrapOutputJSON conflict distPath: { root: 'dist-swc', }, }, }, }; const noStyledConfig = { ...commonConfig, builderConfig: { ...commonConfig.builderConfig, tools: { ...commonConfig.builderConfig.tools, styledComponents: false as const, }, }, }; test('should allow to disable styled-components when use swc plugin', async () => { const builder = await build({ ...noStyledConfig, plugins: [builderPluginSwc()], }); const files = await builder.unwrapOutputJSON(); const content = files[ Object.keys(files).find( file => file.includes('static/js') && file.endsWith('.js'), )! ]; expect(content).toContain('div('); }); test('should transform styled-components by default when use swc plugin', async () => { const builder = await build({ ...commonConfig, plugins: [builderPluginSwc()], }); const files = await builder.unwrapOutputJSON(); const content = files[ Object.keys(files).find( file => file.includes('static/js') && file.endsWith('.js'), )! ]; expect(content).toContain('div.withConfig'); });
730
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/styled-component/index.test.ts
import path from 'path'; import { build } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; import { expect } from '@modern-js/e2e/playwright'; const commonConfig = { cwd: __dirname, entry: { index: path.resolve(__dirname, './src/main.ts') }, builderConfig: { tools: { bundlerChain: (chain: any) => { chain.externals(['styled-components']); }, }, output: { disableMinimize: true, }, }, }; const noStyledConfig = { ...commonConfig, builderConfig: { ...commonConfig.builderConfig, tools: { ...commonConfig.builderConfig.tools, styledComponents: false as const, }, }, }; // TODO: needs builtin:swc-loader webpackOnlyTest('should allow to disable styled-components', async () => { const builder = await build(noStyledConfig); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.js'))!]; expect(content).toContain('div('); }); // TODO: needs builtin:swc-loader webpackOnlyTest('should transform styled-components by default', async () => { const builder = await build(commonConfig); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.js'))!]; expect(content).toContain('div.withConfig'); });
732
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/stylus-rem/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { builderPluginStylus } from '@modern-js/builder-plugin-stylus'; test('should compile stylus and rem correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, plugins: [builderPluginStylus()], builderConfig: { output: { convertToRem: true, }, }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; if (builder.providerType === 'rspack') { expect(content).toEqual( 'body{color:red;font:.28rem Arial,sans-serif}.title-class-_7352f{font-size:.28rem}', ); } else { expect(content).toEqual( 'body{color:red;font:.28rem Arial,sans-serif}.title-class-XQprme{font-size:.28rem}', ); } });
736
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/stylus/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { builderPluginStylus } from '@modern-js/builder-plugin-stylus'; test('should compile stylus correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, plugins: [builderPluginStylus()], }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => file.endsWith('.css'))!]; if (builder.providerType === 'rspack') { expect(content).toEqual( 'body{color:red;font:14px Arial,sans-serif}.title-class-_7352f{font-size:14px}', ); } else { expect(content).toEqual( 'body{color:red;font:14px Arial,sans-serif}.title-class-XQprme{font-size:14px}', ); } });
740
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/svg/svg.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = __dirname; test('svg (default)', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'svg'), entry: { main: join(fixtures, 'svg', 'src/index.js'), }, runServer: true, }); await page.goto(getHrefByEntryName('main', builder.port)); // test svgr(namedExport) await expect( page.evaluate(`document.getElementById('test-svg').tagName === 'svg'`), ).resolves.toBeTruthy(); // test svg asset await expect( page.evaluate( `document.getElementById('test-img').src.startsWith('data:image/svg')`, ), ).resolves.toBeTruthy(); // test svg asset in css await expect( page.evaluate( `getComputedStyle(document.getElementById('test-css')).backgroundImage.includes('url("data:image/svg')`, ), ).resolves.toBeTruthy(); builder.close(); }); test('svg (defaultExport component)', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'svg-default-export-component'), entry: { main: join(fixtures, 'svg-default-export-component', 'src/index.js'), }, runServer: true, builderConfig: { output: { svgDefaultExport: 'component', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); await expect( page.evaluate(`document.getElementById('test-svg').tagName === 'svg'`), ).resolves.toBeTruthy(); builder.close(); }); test('svg (url)', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'svg-url'), entry: { main: join(fixtures, 'svg-url', 'src/index.js'), }, runServer: true, }); await page.goto(getHrefByEntryName('main', builder.port)); // test svg asset await expect( page.evaluate( `document.getElementById('test-img').src.includes('static/svg/app')`, ), ).resolves.toBeTruthy(); // test svg asset in css await expect( page.evaluate( `getComputedStyle(document.getElementById('test-css')).backgroundImage.includes('static/svg/app')`, ), ).resolves.toBeTruthy(); builder.close(); }); // It's an old bug when use svgr in css and external react. test('svg (external react)', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'svg-external-react'), entry: { main: join(fixtures, 'svg-external-react', 'src/index.js'), }, runServer: true, builderConfig: { output: { externals: { react: 'React', 'react-dom': 'ReactDOM', }, }, html: { template: './static/index.html', }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); // test svgr(namedExport) await expect( page.evaluate(`document.getElementById('test-svg').tagName === 'svg'`), ).resolves.toBeTruthy(); // test svg asset await expect( page.evaluate( `document.getElementById('test-img').src.startsWith('data:image/svg')`, ), ).resolves.toBeTruthy(); // test svg asset in css await expect( page.evaluate( `getComputedStyle(document.getElementById('test-css')).backgroundImage.includes('url("data:image/svg')`, ), ).resolves.toBeTruthy(); builder.close(); }); test('svg (disableSvgr)', async ({ page }) => { const builder = await build({ cwd: join(fixtures, 'svg-assets'), entry: { main: join(fixtures, 'svg-assets', 'src/index.js'), }, runServer: true, builderConfig: { output: { disableSvgr: true, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); // test svg asset await expect( page.evaluate( `document.getElementById('test-img').src.includes('static/svg/app')`, ), ).resolves.toBeTruthy(); // test svg asset in css await expect( page.evaluate( `getComputedStyle(document.getElementById('test-css')).backgroundImage.includes('static/svg/app')`, ), ).resolves.toBeTruthy(); builder.close(); });
741
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/svg/svgo.test.ts
import { join } from 'path'; import { readFileSync } from 'fs'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; test('should preserve viewBox after svgo minification', async () => { const fixture = join(__dirname, 'svgo-minify-view-box'); const buildOpts = { cwd: fixture, entry: { main: join(fixture, 'src/index.jsx'), }, }; const builder = await build(buildOpts); const files = await builder.unwrapOutputJSON(); const mainJs = Object.keys(files).find( file => file.includes('/main.') && file.endsWith('.js'), ); const content = readFileSync(mainJs!, 'utf-8'); expect( content.includes('width:120,height:120,viewBox:"0 0 120 120"'), ).toBeTruthy(); }); test('should add id prefix after svgo minification', async () => { const fixture = join(__dirname, 'svgo-minify-id-prefix'); const buildOpts = { cwd: fixture, entry: { main: join(fixture, 'src/index.jsx'), }, }; const builder = await build(buildOpts); const files = await builder.unwrapOutputJSON(); const mainJs = Object.keys(files).find( file => file.includes('/main.') && file.endsWith('.js'), ); const content = readFileSync(mainJs!, 'utf-8'); expect( content.includes('"linearGradient",{id:"idPrefix_svg__a"}'), ).toBeTruthy(); });
766
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/swc/index.swc.test.ts
import assert from 'assert'; import * as path from 'path'; import { readFileSync } from 'fs'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { builderPluginSwc } from '@modern-js/builder-plugin-swc'; test('should run SWC compilation correctly', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/main.ts'), }, plugins: [builderPluginSwc()], runServer: true, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.student')).toEqual({ name: 'xxx', id: 1, age: 10, school: 'yyy', }); await builder.close(); }); test('should optimize lodash bundle size', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/main.ts'), }, plugins: [builderPluginSwc()], runServer: true, builderConfig: { output: { polyfill: 'entry', }, }, }); await page.goto(getHrefByEntryName('index', builder.port)); const files = await builder.unwrapOutputJSON(); const lodashBundle = Object.keys(files).find(file => file.includes('lib-lodash'), ); assert(lodashBundle); const bundleSize = readFileSync(lodashBundle, 'utf-8').length / 1024; expect(bundleSize < 10).toBeTruthy(); await builder.close(); }); test('should use define for class', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/main.ts'), }, plugins: [ builderPluginSwc({ overrides: [ { test: /override.ts/, jsc: { transform: { useDefineForClassFields: false, }, }, }, ], jsc: { transform: { useDefineForClassFields: true, }, }, }), ], builderConfig: { output: { disableMinimize: true, }, }, runServer: true, }); const { content: file } = await builder.getIndexFile(); // this is because setting useDefineForClassFields to false expect(file.includes('this.bar = 1')).toBe(true); // should not affect normal modules expect( file.includes('_define_property(_assert_this_initialized(_this), "id", 1)'), ).toBe(true); await builder.close(); }); test('core-js-entry', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/core-js-entry.ts'), }, plugins: [ builderPluginSwc({ env: { targets: 'ie 9', mode: 'entry', }, }), ], builderConfig: { output: { disableMinimize: true, }, }, runServer: true, }); await builder.close(); }); test('core-js-usage', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/core-js-usage.ts'), }, plugins: [ builderPluginSwc({ env: { targets: 'ie 9', mode: 'usage', }, }), ], builderConfig: { output: { disableMinimize: true, }, }, runServer: true, }); await builder.close(); });
776
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/tools/pug
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/tools/pug/tests/index.test.ts
import { join, resolve } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; const fixtures = resolve(__dirname, '../'); test('pug', async ({ page }) => { const builder = await build({ cwd: fixtures, entry: { main: join(fixtures, 'src/index.ts'), }, runServer: true, builderConfig: { html: { template: './static/index.pug', }, tools: { pug: true, }, }, }); await page.goto(getHrefByEntryName('main', builder.port)); const testPug = page.locator('#test-pug'); await expect(testPug).toHaveText('Pug source code!'); const testEl = page.locator('#test'); await expect(testEl).toHaveText('Hello Builder!'); builder.close(); });
777
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/top-level-await/index.swc.test.ts
import * as path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { builderPluginSwc } from '@modern-js/builder-plugin-swc'; test('should run top level await correctly when using SWC', async ({ page, }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts'), }, plugins: [builderPluginSwc()], runServer: true, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.foo')).toEqual('hello'); builder.close(); });
778
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/top-level-await/index.test.ts
import * as path from 'path'; import { expect } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { webpackOnlyTest } from '../../scripts/helper'; webpackOnlyTest('should run top level await correctly', async ({ page }) => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts'), }, runServer: true, }); await page.goto(getHrefByEntryName('index', builder.port)); expect(await page.evaluate('window.foo')).toEqual('hello'); builder.close(); });
782
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/ts-loader/index.test.ts
import path from 'path'; import { expect } from '@modern-js/e2e/playwright'; import { webpackOnlyTest } from '@scripts/helper'; import { build } from '@scripts/shared'; webpackOnlyTest('build pass with default ts-loader options', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts') }, builderConfig: { tools: { tsLoader: {}, }, }, }); const files = await builder.unwrapOutputJSON(); const output = files[Object.keys(files).find(file => /index\.\w+\.js/.test(file))!]; expect(output).toBeTruthy(); });
786
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/typescript/index.test.ts
import path from 'path'; import { expect } from '@modern-js/e2e/playwright'; import { webpackOnlyTest } from '@scripts/helper'; import { build } from '@scripts/shared'; webpackOnlyTest('should compile const enum correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.ts') }, builderConfig: { output: { polyfill: 'off', }, }, }); const files = await builder.unwrapOutputJSON(); const content = files[Object.keys(files).find(file => /index\.\w+\.js/.test(file))!]; expect(content.includes('console.log("fish is :",0)')).toBeTruthy(); });
790
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/vue/index.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { builderPluginVue } from '@modern-js/builder-plugin-vue'; test('should build basic Vue sfc correctly', async ({ page }) => { const root = join(__dirname, 'sfc-basic'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button1 = page.locator('#button1'); const button2 = page.locator('#button2'); await expect(button1).toHaveText('A: 0'); await expect(button2).toHaveText('B: 0'); builder.close(); }); test('should build Vue sfc style correctly', async ({ page }) => { const root = join(__dirname, 'sfc-style'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button = page.locator('#button'); await expect(button).toHaveCSS('color', 'rgb(255, 0, 0)'); const body = page.locator('body'); await expect(body).toHaveCSS('background-color', 'rgb(0, 0, 255)'); builder.close(); }); test('should build basic Vue jsx correctly', async ({ page }) => { const root = join(__dirname, 'jsx-basic'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button1 = page.locator('#button1'); await expect(button1).toHaveText('A: 0'); builder.close(); }); test('should build Vue sfc with lang="ts" correctly', async ({ page }) => { const root = join(__dirname, 'sfc-lang-ts'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button = page.locator('#button'); await expect(button).toHaveText('count: 0 foo: bar'); builder.close(); }); test('should build Vue sfc with lang="jsx" correctly', async ({ page }) => { const root = join(__dirname, 'sfc-lang-jsx'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button = page.locator('#button'); await expect(button).toHaveText('0'); const foo = page.locator('#foo'); await expect(foo).toHaveText('Foo'); builder.close(); }); test('should build Vue sfc with lang="tsx" correctly', async ({ page }) => { const root = join(__dirname, 'sfc-lang-tsx'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button = page.locator('#button'); await expect(button).toHaveText('0'); const foo = page.locator('#foo'); await expect(foo).toHaveText('Foo'); builder.close(); });
806
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/vue2/index.test.ts
import { join } from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; import { builderPluginVue2 } from '@modern-js/builder-plugin-vue2'; test('should build basic Vue sfc correctly', async ({ page }) => { const root = join(__dirname, 'sfc-basic'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue2()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button1 = page.locator('#button1'); const button2 = page.locator('#button2'); await expect(button1).toHaveText('A: 0'); await expect(button2).toHaveText('B: 0'); builder.close(); }); test('should build Vue sfc style correctly', async ({ page }) => { const root = join(__dirname, 'sfc-style'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue2()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button = page.locator('#button'); await expect(button).toHaveCSS('color', 'rgb(255, 0, 0)'); const body = page.locator('body'); await expect(body).toHaveCSS('background-color', 'rgb(0, 0, 255)'); builder.close(); }); test('should build basic Vue jsx correctly', async ({ page }) => { const root = join(__dirname, 'jsx-basic'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue2()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button1 = page.locator('#button1'); await expect(button1).toHaveText('A: 0'); builder.close(); }); test('should build Vue sfc with lang="ts" correctly', async ({ page }) => { const root = join(__dirname, 'sfc-lang-ts'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue2()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button = page.locator('#button'); await expect(button).toHaveText('count: 0 foo: bar'); builder.close(); }); test('should build Vue sfc with lang="jsx" correctly', async ({ page }) => { const root = join(__dirname, 'sfc-lang-jsx'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue2()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button = page.locator('#button'); await expect(button).toHaveText('0'); const foo = page.locator('#foo'); await expect(foo).toHaveText('Foo'); builder.close(); }); test('should build Vue sfc with lang="tsx" correctly', async ({ page }) => { const root = join(__dirname, 'sfc-lang-tsx'); const builder = await build({ cwd: root, entry: { main: join(root, 'src/index.js'), }, runServer: true, plugins: [builderPluginVue2()], }); await page.goto(getHrefByEntryName('main', builder.port)); const button = page.locator('#button'); await expect(button).toHaveText('0'); const foo = page.locator('#foo'); await expect(foo).toHaveText('Foo'); builder.close(); });
822
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/wasm/index.test.ts
import path, { join } from 'path'; import { test, expect } from '@modern-js/e2e/playwright'; import { build, getHrefByEntryName } from '@scripts/shared'; test('should allow to import wasm file', async ({ page }) => { const root = join(__dirname, 'wasm-basic'); const builder = await build({ cwd: root, entry: { main: path.resolve(root, 'src/index.js') }, runServer: true, }); const files = await builder.unwrapOutputJSON(); const wasmFile = Object.keys(files).find(file => file.endsWith('.module.wasm'), ); expect(wasmFile).toBeTruthy(); expect(wasmFile?.includes('static/wasm/')).toBeTruthy(); await page.goto(getHrefByEntryName('main', builder.port)); await page.waitForFunction(() => { return Boolean(document.querySelector('#root')?.innerHTML); }); const locator = page.locator('#root'); await expect(locator).toHaveText('6'); builder.close(); }); test('should allow to dynamic import wasm file', async () => { const root = join(__dirname, 'wasm-async'); const builder = await build({ cwd: root, entry: { main: path.resolve(root, 'src/index.js') }, }); const files = await builder.unwrapOutputJSON(); const wasmFile = Object.keys(files).find(file => file.endsWith('.module.wasm'), ); expect(wasmFile).toBeTruthy(); expect(wasmFile?.includes('static/wasm/')).toBeTruthy(); }); test('should allow to use new URL to get path of wasm file', async ({ page, }) => { const root = join(__dirname, 'wasm-url'); const builder = await build({ cwd: root, entry: { main: path.resolve(root, 'src/index.js') }, runServer: true, }); const files = await builder.unwrapOutputJSON(); const wasmFile = Object.keys(files).find(file => file.endsWith('.module.wasm'), ); expect(wasmFile).toBeTruthy(); expect(wasmFile?.includes('static/wasm/')).toBeTruthy(); await page.goto(getHrefByEntryName('main', builder.port)); await page.waitForFunction(() => { return Boolean(document.querySelector('#root')?.innerHTML); }); await expect( page.evaluate(`document.querySelector('#root').innerHTML`), ).resolves.toMatch(/\/static\/wasm\/\w+\.module\.wasm/); builder.close(); });
828
0
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases
petrpan-code/web-infra-dev/modern.js/tests/e2e/builder/cases/web-worker/index.test.ts
import path from 'path'; import { expect, test } from '@modern-js/e2e/playwright'; import { build } from '@scripts/shared'; import { webpackOnlyTest } from '@scripts/helper'; test('should build web-worker target correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index.js') }, target: 'web-worker', }); const files = await builder.unwrapOutputJSON(); const filenames = Object.keys(files); const jsFiles = filenames.filter(item => item.endsWith('.js')); expect(jsFiles.length).toEqual(1); expect(jsFiles[0].includes('index')).toBeTruthy(); }); // TODO: needs dynamicImportMode: 'eager', webpackOnlyTest( 'should build web-worker target with dynamicImport correctly', async () => { const builder = await build({ cwd: __dirname, entry: { index: path.resolve(__dirname, './src/index2.js') }, target: 'web-worker', }); const files = await builder.unwrapOutputJSON(); const filenames = Object.keys(files); const jsFiles = filenames.filter(item => item.endsWith('.js')); expect(jsFiles.length).toEqual(1); expect(jsFiles[0].includes('index')).toBeTruthy(); }, );
886
0
petrpan-code/web-infra-dev/modern.js/tests/integration/alias-set
petrpan-code/web-infra-dev/modern.js/tests/integration/alias-set/tests/index.test.ts
import fs from 'fs'; import path from 'path'; import puppeteer from 'puppeteer'; import { launchApp, killApp, getPort, launchOptions, modernBuild, } from '../../../utils/modernTestUtils'; const appDir = path.resolve(__dirname, '../'); function existsSync(filePath: string) { return fs.existsSync(path.join(appDir, 'dist', filePath)); } describe('alias set build', () => { test(`should get right alias build!`, async () => { const buildRes = await modernBuild(appDir); expect(buildRes.code === 0).toBe(true); expect(existsSync('route.json')).toBe(true); expect(existsSync('html/main/index.html')).toBe(true); }); }); describe('alias set dev', () => { test(`should render page correctly`, async () => { const appPort = await getPort(); const app = await launchApp( appDir, appPort, {}, { // FIXME: disable the fast refresh plugin to avoid the `require` not found issue. FAST_REFRESH: 'false', }, ); const errors = []; const browser = await puppeteer.launch(launchOptions as any); const page = await browser.newPage(); page.on('pageerror', error => errors.push(error.message)); await page.goto(`http://localhost:${appPort}`, { waitUntil: ['networkidle0'], }); const root = await page.$('#root'); const targetText = await page.evaluate(el => el?.textContent, root); expect(targetText?.trim()).toEqual('Hello Modern.js! 1'); expect(errors.length).toEqual(0); browser.close(); await killApp(app); }); });
894
0
petrpan-code/web-infra-dev/modern.js/tests/integration/api-service-koa/api
petrpan-code/web-infra-dev/modern.js/tests/integration/api-service-koa/api/tests/context.test.ts
describe('context', () => { it('should support context', async () => { const { get: getContext } = await import('../context'); const data = await getContext(); expect(data).toEqual({ message: 'Hello Modern.js', }); }); });
895
0
petrpan-code/web-infra-dev/modern.js/tests/integration/api-service-koa/api
petrpan-code/web-infra-dev/modern.js/tests/integration/api-service-koa/api/tests/index.test.ts
import { testBff } from '@modern-js/runtime/testing/bff'; describe('basic usage', () => { it('should support get', async () => { const { get } = await import('..'); const data = await get(); expect(data).toEqual({ message: 'Hello Modern.js', }); }); it('should support testBff', async () => { const { get } = await import('..'); await testBff(get) .expect('Content-Type', /json/) .expect(200, { message: 'Hello Modern.js' }); }); it('should support testBff by api', async () => { await testBff() .post('/api') .send() .expect(200, { message: 'Hello Modern.js' }); }); });
896
0
petrpan-code/web-infra-dev/modern.js/tests/integration/api-service-koa/api
petrpan-code/web-infra-dev/modern.js/tests/integration/api-service-koa/api/tests/mock-context.test.ts
jest.mock('@modern-js/runtime/koa', () => { return { __esModule: true, useContext: jest.fn(() => ({ message: 'hello', })), }; }); describe('context', () => { it('should support mock useContext', async () => { const { post: postContext } = await import('../context'); const data = await postContext(); expect(data.message).toEqual('hello'); }); });
897
0
petrpan-code/web-infra-dev/modern.js/tests/integration/api-service-koa
petrpan-code/web-infra-dev/modern.js/tests/integration/api-service-koa/tests/index.test.ts
import dns from 'node:dns'; import path from 'path'; import { getPort, launchApp, killApp, modernBuild, modernServe, } from '../../../utils/modernTestUtils'; import 'isomorphic-fetch'; dns.setDefaultResultOrder('ipv4first'); describe('api-service in dev', () => { let port = 8080; const prefix = '/api'; const host = `http://localhost`; const appPath = path.resolve(__dirname, '../'); let app: any; beforeAll(async () => { jest.setTimeout(1000 * 60 * 2); port = await getPort(); app = await launchApp(appPath, port, { cwd: appPath, }); }); test('support get method', async () => { const res = await fetch(`${host}:${port}${prefix}`); const data = await res.json(); expect(data).toEqual({ message: 'Hello Modern.js', }); }); test('support post method', async () => { const res = await fetch(`${host}:${port}${prefix}`, { method: 'POST', }); const data = await res.json(); expect(data).toEqual({ message: 'Hello Modern.js', }); }); test('support useContext', async () => { const res = await fetch(`${host}:${port}${prefix}/context`); const info = await res.json(); expect(res.headers.get('x-id')).toBe('1'); expect(info.message).toBe('Hello Modern.js'); }); afterAll(async () => { await killApp(app); }); }); describe('api-service in prod', () => { let port = 8080; const prefix = '/api'; const host = `http://localhost`; const appPath = path.resolve(__dirname, '../'); let app: any; beforeAll(async () => { port = await getPort(); await modernBuild(appPath, [], { cwd: appPath, }); app = await modernServe(appPath, port, { cwd: appPath, }); }); test('support get method', async () => { const res = await fetch(`${host}:${port}${prefix}`); const data = await res.json(); expect(data).toEqual({ message: 'Hello Modern.js', }); }); test('support post method', async () => { const res = await fetch(`${host}:${port}${prefix}`, { method: 'POST', }); const data = await res.json(); expect(data).toEqual({ message: 'Hello Modern.js', }); }); test('support useContext', async () => { const res = await fetch(`${host}:${port}${prefix}/context`); const info = await res.json(); expect(res.headers.get('x-id')).toBe('1'); expect(info.message).toBe('Hello Modern.js'); }); afterAll(async () => { await killApp(app); }); });
914
0
petrpan-code/web-infra-dev/modern.js/tests/integration/app-document
petrpan-code/web-infra-dev/modern.js/tests/integration/app-document/tests/index.test.ts
import fs from 'fs'; import path from 'path'; import puppeteer, { Browser, Page } from 'puppeteer'; import { launchApp, killApp, getPort, modernBuild, launchOptions, } from '../../../utils/modernTestUtils'; import { printFileTogether } from '../../../utils/printDir'; import { SequenceWait } from '../../../utils/testInSequence'; const appDir = path.resolve(__dirname, '../'); function existsSync(filePath: string) { return fs.existsSync(path.join(appDir, 'dist', filePath)); } describe('test dev and build', () => { const curSequenceWait = new SequenceWait(); curSequenceWait.add('test-dev'); curSequenceWait.add('test-rem'); describe('test build', () => { let buildRes: any; beforeAll(async () => { buildRes = await modernBuild(appDir); }); afterAll(() => { curSequenceWait.done('test-dev'); }); test(`should get right alias build!`, async () => { if (buildRes.code !== 0) { console.log('\n===> build failed, stdout: ', buildRes.stdout); console.log('\n===> build failed, stderr: ', buildRes.stderr); } expect(buildRes.code).toEqual(0); expect(existsSync('route.json')).toBe(true); expect(existsSync('html/test/index.html')).toBe(true); expect(existsSync('html/sub/index.html')).toBe(true); }); test('should have the test html and the correct content', async () => { const htmlNoDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/test/index.html'), 'utf-8', ); expect(htmlNoDoc.includes('<div id="root"><!--<?- html ?>--></div>')); }); test('should have the sub html and the correct content', async () => { const htmlWithDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/sub/index.html'), 'utf-8', ); expect(htmlWithDoc.includes('<div id="root"><!--<?- html ?>--><h1')); }); test('should has comment in Head', async () => { const htmlWithDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/sub/index.html'), 'utf-8', ); expect(htmlWithDoc.includes('<!-- COMMENT BY APP -->')).toBe(true); expect(htmlWithDoc.includes('== COMMENT BY APP in inline ==')).toBe(true); expect(htmlWithDoc.includes('== COMMENT BY APP but inline ==')).toBe( false, ); }); test('should has style in Head', async () => { const htmlWithDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/sub/index.html'), 'utf-8', ); expect(htmlWithDoc.includes('.logo-spin>div:last-child')).toBe(true); }); test('should has lang property in html', async () => { const htmlWithDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/sub/index.html'), 'utf-8', ); expect(htmlWithDoc.includes(`html lang="cn"`)).toBe(true); }); test('should has dir property in body', async () => { const htmlWithDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/sub/index.html'), 'utf-8', ); expect(htmlWithDoc.includes(`body dir="ltr"`)).toBe(true); }); test('should has class property in root div', async () => { const htmlWithDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/sub/index.html'), 'utf-8', ); expect(htmlWithDoc.includes(`div id="root" class="root"`)).toBe(true); }); test('should has class property in root div', async () => { const htmlWithDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/sub/index.html'), 'utf-8', ); expect(htmlWithDoc.includes(`head class="head"`)).toBe(true); }); test('when not set partial html should normal', async () => { const normalHtml = fs.readFileSync( path.join(appDir, 'dist', 'html/differentProperities/index.html'), 'utf-8', ); const partialPlaceholder = encodeURIComponent( '<!--<?- partials.top ?>-->', ); expect(new RegExp(partialPlaceholder).test(normalHtml)).toBe(false); }); test('should injected partial html content to html', async () => { const htmlWithDoc = fs.readFileSync( path.join(appDir, 'dist', 'html/sub/index.html'), 'utf-8', ); expect( /<head class="head"><script>window.abc="hjk"<\/script>/.test( htmlWithDoc, ), ).toBe(true); expect( /<head[\s\S]*<script>console.log\("abc"\)<\/script>[\s\S]*<\/head>/.test( htmlWithDoc, ), ).toBe(true); expect( /<body[\s\S]*<script>console.log\(abc\)<\/script>[\s\S]*<\/body>/.test( htmlWithDoc, ), ).toBe(true); }); }); describe('test dev', () => { let app: any; let appPort: number; let errors; let browser: Browser; let page: Page; beforeAll(async () => { await curSequenceWait.waitUntil('test-dev'); appPort = await getPort(); app = await launchApp(appDir, appPort, {}, {}); errors = []; browser = await puppeteer.launch(launchOptions as any); page = await browser.newPage(); page.on('pageerror', error => { errors.push(error.message); }); }); afterAll(async () => { await killApp(app); await page.close(); await browser.close(); curSequenceWait.done('test-rem'); }); test(`should render page test correctly`, async () => { await page.goto(`http://localhost:${appPort}/test`, { waitUntil: ['networkidle0'], }); const root = await page.$('#root'); const targetText = await page.evaluate(el => el?.textContent, root); expect(targetText?.trim()).toEqual('A'); expect(errors.length).toEqual(0); }); test(`should render page sub correctly`, async () => { printFileTogether(path.join(__dirname, '../node_modules/.modern-js')); await page.goto(`http://localhost:${appPort}/sub`, { waitUntil: ['networkidle0'], }); await page.waitForSelector('#root a'); const root = await page.$('#root'); const targetText = await page.evaluate(el => el?.textContent, root); expect(targetText?.trim()).toEqual('去 A去 B'); expect(errors.length).toEqual(0); }); test(`should render page sub route a correctly`, async () => { printFileTogether(path.join(__dirname, '../node_modules/.modern-js')); await page.goto(`http://localhost:${appPort}/sub/a`, { waitUntil: ['networkidle0'], }); await page.waitForSelector('#root a'); const root = await page.$('#root'); const targetText = await page.evaluate(el => el?.textContent, root); expect(targetText?.trim()).toEqual('去 A去 B'); expect(errors.length).toEqual(0); }); }); describe('fix rem', () => { beforeAll(async () => { await curSequenceWait.waitUntil('test-rem'); await modernBuild(appDir, ['-c', 'modern-rem.config.ts']); }); test('should add rem resource correct', async () => { const htmlNoDoc = fs.readFileSync( path.join(appDir, 'dist-1', 'html/test/index.html'), 'utf-8', ); expect(htmlNoDoc.includes('/static/js/convert-rem.')); }); }); });
920
0
petrpan-code/web-infra-dev/modern.js/tests/integration/asset-prefix
petrpan-code/web-infra-dev/modern.js/tests/integration/asset-prefix/tests/index.test.ts
import path from 'path'; import { readFileSync } from 'fs'; import puppeteer, { Browser, Page } from 'puppeteer'; import { launchApp, killApp, getPort, launchOptions, } from '../../../utils/modernTestUtils'; const DEFAULT_DEV_HOST = 'localhost'; const appDir = path.resolve(__dirname, '../'); describe('asset prefix', () => { let app: any; let appPort: number; let errors; let browser: Browser; let page: Page; beforeAll(async () => { appPort = await getPort(); app = await launchApp(appDir, appPort, {}, {}); errors = []; browser = await puppeteer.launch(launchOptions as any); page = await browser.newPage(); page.on('pageerror', error => { errors.push(error.message); }); }); afterAll(async () => { await killApp(app); await page.close(); await browser.close(); }); test(`should generate assetPrefix correctly when dev.assetPrefix is true`, async () => { const HTML = readFileSync( path.join(appDir, 'dist/html/main/index.html'), 'utf-8', ); expect( HTML.includes(`http://${DEFAULT_DEV_HOST}:${appPort}/static/js/`), ).toBeTruthy(); }); test(`should inject window.__assetPrefix__ global variable`, async () => { const expected = `http://${DEFAULT_DEV_HOST}:${appPort}`; const mainJs = readFileSync( path.join(appDir, 'dist/static/js/main.js'), 'utf-8', ); expect( mainJs.includes(`window.__assetPrefix__ = '${expected}';`), ).toBeTruthy(); await page.goto(`${expected}`); const assetPrefix = await page.evaluate(() => { // @ts-expect-error return window.__assetPrefix__; }); expect(assetPrefix).toEqual(expected); }); });
926
0
petrpan-code/web-infra-dev/modern.js/tests/integration/async-entry
petrpan-code/web-infra-dev/modern.js/tests/integration/async-entry/tests/index.test.ts
import path from 'path'; import { readFileSync } from 'fs'; import { modernBuild } from '../../../utils/modernTestUtils'; describe('generate async entry', () => { test(`should generate async entry correctly`, async () => { const appDir = path.resolve(__dirname, '..'); await modernBuild(appDir); expect( readFileSync( path.resolve(appDir, `node_modules/.modern-js/main/bootstrap.jsx`), 'utf8', ), ).toContain(`import App from '@_modern_js_src/App';`); expect( readFileSync( path.resolve(appDir, `node_modules/.modern-js/main/index.jsx`), 'utf8', ), ).toContain(`import('./bootstrap.jsx');`); }); });
934
0
petrpan-code/web-infra-dev/modern.js/tests/integration/basic-app
petrpan-code/web-infra-dev/modern.js/tests/integration/basic-app/tests/index.test.ts
import fs from 'fs'; import path from 'path'; import puppeteer from 'puppeteer'; import { launchApp, killApp, getPort, modernBuild, modernServe, launchOptions, } from '../../../utils/modernTestUtils'; import { SequenceWait } from '../../../utils/testInSequence'; const appDir = path.resolve(__dirname, '../'); function existsSync(filePath: string) { return fs.existsSync(path.join(appDir, 'dist', filePath)); } const curSequence = new SequenceWait(); curSequence.add('dev'); describe('test dev', () => { afterAll(async () => { await curSequence.done('dev'); }); test(`should render page correctly`, async () => { const appPort = await getPort(); const app = await launchApp(appDir, appPort, {}, {}); const errors = []; const browser = await puppeteer.launch(launchOptions as any); const page = await browser.newPage(); page.on('pageerror', error => { errors.push(error.message); }); await page.goto(`http://localhost:${appPort}`, { waitUntil: ['networkidle0'], }); const root = await page.$('.description'); const targetText = await page.evaluate(el => el?.textContent, root); expect(targetText?.trim()).toEqual('Get started by editing src/App.tsx'); expect(errors.length).toEqual(0); await killApp(app); await page.close(); await browser.close(); }); }); describe('test build', () => { let port = 8080; let buildRes: { code: number }; let app: any; beforeAll(async () => { await curSequence.waitUntil('dev'); port = await getPort(); buildRes = await modernBuild(appDir); app = await modernServe(appDir, port, { cwd: appDir, }); }); afterAll(async () => { await killApp(app); }); test(`should get right alias build!`, async () => { expect(buildRes.code === 0).toBe(true); expect(existsSync('route.json')).toBe(true); expect(existsSync('html/main/index.html')).toBe(true); }); test('should support enableInlineScripts', async () => { const host = `http://localhost`; expect(buildRes.code === 0).toBe(true); const browser = await puppeteer.launch(launchOptions as any); const page = await browser.newPage(); await page.goto(`${host}:${port}`); const description = await page.$('.description'); const targetText = await page.evaluate(el => el?.textContent, description); expect(targetText?.trim()).toEqual('Get started by editing src/App.tsx'); await page.close(); await browser.close(); }); });
946
0
petrpan-code/web-infra-dev/modern.js/tests/integration/bff-express
petrpan-code/web-infra-dev/modern.js/tests/integration/bff-express/tests/index.test.ts
import dns from 'node:dns'; import path from 'path'; import puppeteer, { Browser, Page } from 'puppeteer'; import { getPort, launchApp, killApp, modernBuild, modernServe, launchOptions, } from '../../../utils/modernTestUtils'; import 'isomorphic-fetch'; dns.setDefaultResultOrder('ipv4first'); const appDir = path.resolve(__dirname, '../'); describe('bff express in dev', () => { let port = 8080; const SSR_PAGE = 'ssr'; const BASE_PAGE = 'base'; const CUSTOM_PAGE = 'custom-sdk'; const host = `http://localhost`; const prefix = '/bff-api'; let app: any; let page: Page; let browser: Browser; beforeAll(async () => { jest.setTimeout(1000 * 60 * 2); port = await getPort(); app = await launchApp(appDir, port, {}); browser = await puppeteer.launch(launchOptions as any); page = await browser.newPage(); }); test('basic usage', async () => { await page.goto(`${host}:${port}/${BASE_PAGE}`); // Reduce the probability of timeout on windows CI await new Promise(resolve => setTimeout(resolve, 3000)); const text = await page.$eval('.hello', el => el?.textContent); expect(text).toBe('Hello Modern.js'); }); test('basic usage with ssr', async () => { await page.goto(`${host}:${port}/${SSR_PAGE}`); await new Promise(resolve => setTimeout(resolve, 3000)); const text1 = await page.$eval('.hello', el => el?.textContent); expect(text1).toBe('Hello Modern.js'); }); test('support useContext', async () => { const res = await fetch(`${host}:${port}${prefix}/context`); const info = await res.json(); expect(res.headers.get('x-id')).toBe('1'); expect(info.message).toBe('Hello Modern.js'); }); test('support _app.ts', async () => { const res = await fetch(`${host}:${port}${prefix}/foo`); const text = await res.text(); expect(text).toBe('foo'); }); test('support custom sdk', async () => { await page.goto(`${host}:${port}/${CUSTOM_PAGE}`); await new Promise(resolve => setTimeout(resolve, 1000)); const text = await page.$eval('.hello', el => el?.textContent); expect(text).toBe('Hello Custom SDK'); }); afterAll(async () => { await killApp(app); await page.close(); await browser.close(); }); }); describe('bff express in prod', () => { let port = 8080; const SSR_PAGE = 'ssr'; const BASE_PAGE = 'base'; const CUSTOM_PAGE = 'custom-sdk'; const host = `http://localhost`; const prefix = '/bff-api'; let app: any; let page: Page; let browser: Browser; beforeAll(async () => { port = await getPort(); await modernBuild(appDir, [], {}); app = await modernServe(appDir, port, {}); browser = await puppeteer.launch(launchOptions as any); page = await browser.newPage(); }); // FIXME: Skipped because this test often times out on Windows test.skip('basic usage', async () => { await page.goto(`${host}:${port}/${BASE_PAGE}`); const text1 = await page.$eval('.hello', el => el?.textContent); expect(text1).toBe('bff-express'); await new Promise(resolve => setTimeout(resolve, 300)); const text2 = await page.$eval('.hello', el => el?.textContent); expect(text2).toBe('Hello Modern.js'); }); // FIXME: This test unit is probably crazy // when you run it on local, It is normal. // when you run it on test, It is crazy. test.skip('basic usage with ssr', async () => { await page.goto(`${host}:${port}/${SSR_PAGE}`); const text1 = await page.$eval('.hello', el => el?.textContent); expect(text1).toBe('Hello Modern.js'); }); test('support useContext', async () => { const res = await fetch(`${host}:${port}${prefix}/context`); const info = await res.json(); expect(res.headers.get('x-id')).toBe('1'); expect(info.message).toBe('Hello Modern.js'); }); test('support _app.ts', async () => { const res = await fetch(`${host}:${port}${prefix}/foo`); const text = await res.text(); expect(text).toBe('foo'); }); test('support custom sdk', async () => { await page.goto(`${host}:${port}/${CUSTOM_PAGE}`); await new Promise(resolve => setTimeout(resolve, 1000)); const text = await page.$eval('.hello', el => el?.textContent); expect(text).toBe('Hello Custom SDK'); }); afterAll(async () => { await killApp(app); await page.close(); await browser.close(); }); });