Skip to content

Commit f2c123f

Browse files
committed
feat: optimization code
1 parent 440cc1d commit f2c123f

File tree

11 files changed

+118
-67
lines changed

11 files changed

+118
-67
lines changed

src/core/base-plugin.ts

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,70 +5,70 @@ import {
55
StyleTagFactory,
66
DEFAULT_REPLACE_CONFIG,
77
FileCache,
8-
} from '../types'
9-
import { isCSS, escapeRegExp } from '../utils'
8+
} from '../types';
9+
import { isCSS, escapeRegExp } from '../utils';
1010

1111
export class BasePlugin {
12-
protected cssStyleCache: FileCache = {}
12+
protected cssStyleCache: FileCache = {};
1313

1414
protected get replaceConfig() {
15-
return this.config.replace || DEFAULT_REPLACE_CONFIG
15+
return this.config.replace || DEFAULT_REPLACE_CONFIG;
1616
}
1717

1818
protected get styleTagFactory(): StyleTagFactory {
1919
return (
2020
this.config.styleTagFactory ||
2121
(({ style }) => `<style type="text/css">${style}</style>`)
22-
)
22+
);
2323
}
2424

2525
constructor(protected readonly config: Config = {}) {}
2626

2727
protected prepare({ assets }: Compilation) {
2828
Object.keys(assets).forEach((fileName) => {
2929
if (isCSS(fileName) && this.isCurrentFileNeedsToBeInlined(fileName)) {
30-
const source = assets[fileName].source()
31-
this.cssStyleCache[fileName] = typeof source === 'string' ? source : source.toString()
30+
const source = assets[fileName].source();
31+
this.cssStyleCache[fileName] = typeof source === 'string' ? source : source.toString();
3232

3333
if (!this.config.leaveCSSFile) {
34-
delete assets[fileName]
34+
delete assets[fileName];
3535
}
3636
}
37-
})
37+
});
3838
}
3939

4040
protected getCSSStyle({
4141
cssLink,
4242
publicPath,
4343
}: {
44-
cssLink: string
45-
publicPath: string
44+
cssLink: string;
45+
publicPath: string;
4646
}): string | undefined {
4747
// Link pattern: publicPath + fileName + '?' + hash
4848
const fileName = cssLink
4949
.replace(new RegExp(`^${escapeRegExp(publicPath)}`), '')
50-
.replace(/\?.+$/g, '')
50+
.replace(/\?.+$/g, '');
5151

5252
if (this.isCurrentFileNeedsToBeInlined(fileName)) {
53-
const style = this.cssStyleCache[fileName]
53+
const style = this.cssStyleCache[fileName];
5454

5555
if (style === undefined) {
5656
console.error(
57-
`Can not get css style for ${cssLink}. It may be a bug of html-inline-css-webpack-plugin.`,
58-
)
57+
`无法获取 ${cssLink} 的 CSS 样式。这可能是 html-inline-css-webpack-plugin 的一个 bug。`
58+
);
5959
}
6060

61-
return style
61+
return style;
6262
} else {
63-
return undefined
63+
return undefined;
6464
}
6565
}
6666

6767
protected isCurrentFileNeedsToBeInlined(fileName: string): boolean {
6868
if (typeof this.config.filter === 'function') {
69-
return this.config.filter(fileName)
69+
return this.config.filter(fileName);
7070
} else {
71-
return true
71+
return true;
7272
}
7373
}
7474

@@ -77,31 +77,31 @@ export class BasePlugin {
7777
htmlFileName,
7878
style,
7979
}: {
80-
html: string
81-
htmlFileName: string
82-
style: string
80+
html: string;
81+
htmlFileName: string;
82+
style: string;
8383
}) {
8484
const replaceValues = [
8585
this.styleTagFactory({ style }),
8686
this.replaceConfig.target,
87-
]
87+
];
8888

8989
if (this.replaceConfig.position === 'after') {
90-
replaceValues.reverse()
90+
replaceValues.reverse();
9191
}
9292

9393
if (html.indexOf(this.replaceConfig.target) === -1) {
9494
throw new Error(
95-
`Can not inject css style into "${htmlFileName}", as there is not replace target "${this.replaceConfig.target}"`,
96-
)
95+
`无法将 CSS 样式注入到 "${htmlFileName}",因为找不到替换目标 "${this.replaceConfig.target}"`
96+
);
9797
}
9898

99-
return html.replace(this.replaceConfig.target, replaceValues.join(''))
99+
return html.replace(this.replaceConfig.target, replaceValues.join(''));
100100
}
101101

102102
protected cleanUp(html: string) {
103103
return this.replaceConfig.removeTarget
104104
? html.replace(this.replaceConfig.target, '')
105-
: html
105+
: html;
106106
}
107107
}

src/core/rspack.ts

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ import { BasePlugin } from './base-plugin'
55

66
export type ExtraPluginHookData = {
77
plugin: {
8-
options: HtmlRspackPluginOptions;
9-
};
10-
};
8+
options: HtmlRspackPluginOptions
9+
}
10+
}
1111

1212
export interface JsBeforeEmitData {
1313
html: string
@@ -29,13 +29,9 @@ export interface JsBeforeAssetTagGenerationData {
2929
type CSSStyle = string
3030

3131
export class HTMLInlineRspackPlugin extends BasePlugin {
32-
// Using object reference to distinguish styles for multiple files
3332
private cssStyleMap: Map<ExtraPluginHookData['plugin'], CSSStyle[]> = new Map()
3433

3534
private prepareCSSStyle(data: JsBeforeAssetTagGenerationData & ExtraPluginHookData) {
36-
// `prepareCSSStyle` may be called more than once in webpack watch mode.
37-
// https://github.com/Runjuu/html-inline-css-webpack-plugin/issues/30
38-
// https://github.com/Runjuu/html-inline-css-webpack-plugin/issues/13
3935
this.cssStyleMap.clear()
4036

4137
const [...cssAssets] = data.assets.css
@@ -53,7 +49,6 @@ export class HTMLInlineRspackPlugin extends BasePlugin {
5349
this.cssStyleMap.set(data.plugin, [style])
5450
}
5551
const cssLinkIndex = data.assets.css.indexOf(cssLink)
56-
// prevent generate <link /> tag
5752
if (cssLinkIndex !== -1) {
5853
data.assets.css.splice(cssLinkIndex, 1)
5954
}
@@ -63,7 +58,6 @@ export class HTMLInlineRspackPlugin extends BasePlugin {
6358
}
6459

6560
private process(data: JsBeforeEmitData & ExtraPluginHookData) {
66-
// check if current html needs to be inlined
6761
if (this.isCurrentFileNeedsToBeInlined(data.outputName)) {
6862
const cssStyles = this.cssStyleMap.get(data.plugin) || []
6963

@@ -83,24 +77,25 @@ export class HTMLInlineRspackPlugin extends BasePlugin {
8377
compiler.hooks.compilation.tap(
8478
`${TAP_KEY_PREFIX}_compilation`,
8579
(compilation) => {
86-
const hooks = HtmlRspackPlugin.getCompilationHooks(
87-
compilation,
88-
)
80+
const hooks = HtmlRspackPlugin.getCompilationHooks(compilation)
8981

9082
hooks.beforeAssetTagGeneration.tap(
9183
`${TAP_KEY_PREFIX}_beforeAssetTagGeneration`,
9284
(data) => {
9385
this.prepare(compilation)
9486
this.prepareCSSStyle(data)
9587
return data
96-
},
88+
}
9789
)
9890

99-
hooks.beforeEmit.tap(`${TAP_KEY_PREFIX}_beforeEmit`,(data) => {
100-
this.process(data);
101-
return data;
102-
})
103-
},
91+
hooks.beforeEmit.tap(
92+
`${TAP_KEY_PREFIX}_beforeEmit`,
93+
(data) => {
94+
this.process(data)
95+
return data
96+
}
97+
)
98+
}
10499
)
105100
}
106101
}

src/types.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
export interface ReplaceConfig {
2-
position?: 'before' | 'after'
3-
removeTarget?: boolean
4-
target: string
2+
position?: 'before' | 'after';
3+
removeTarget?: boolean;
4+
target: string;
55
}
66

7-
export type StyleTagFactory = (params: { style: string }) => string
7+
export type StyleTagFactory = (params: { style: string }) => string;
88

9-
export const TAP_KEY_PREFIX = 'html-inline-css-rspack-plugin'
9+
export const TAP_KEY_PREFIX = 'html-inline-css-rspack-plugin';
1010

1111
export const DEFAULT_REPLACE_CONFIG: ReplaceConfig = {
1212
target: '</head>',
13-
}
13+
};
1414

1515
export interface Config {
16-
filter?(fileName: string): boolean
17-
leaveCSSFile?: boolean
18-
replace?: ReplaceConfig
19-
styleTagFactory?: StyleTagFactory
16+
filter?(fileName: string): boolean;
17+
leaveCSSFile?: boolean;
18+
replace?: ReplaceConfig;
19+
styleTagFactory?: StyleTagFactory;
2020
}
2121

2222
export interface FileCache {
23-
[fileName: string]: string // file content
23+
[fileName: string]: string; // 文件内容
2424
}

src/utils.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
export function is(filenameExtension: string) {
2-
const reg = new RegExp(`\.${filenameExtension}$`)
3-
return (fileName: string) => reg.test(fileName)
1+
export function is(filenameExtension: string): (fileName: string) => boolean {
2+
const reg = new RegExp(`\\.(${filenameExtension})$`);
3+
return (fileName: string) => reg.test(fileName);
44
}
55

6-
export const isCSS = is('css')
6+
export const isCSS = is('css');
77

88
export function escapeRegExp(string: string): string {
99
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

test/dist/index.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Document</title><script defer src="main.js"></script><link href="main.css" rel="stylesheet"></head><body><h1>Hello, world!</h1></body></html>

test/dist/main.css

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
h1 {
2+
background-color: red;
3+
}
4+

test/dist/main.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
(() => { // webpackBootstrap
2+
"use strict";
3+
var __webpack_modules__ = ({});
4+
/************************************************************************/
5+
// The module cache
6+
var __webpack_module_cache__ = {};
7+
8+
// The require function
9+
function __webpack_require__(moduleId) {
10+
11+
// Check if module is in cache
12+
var cachedModule = __webpack_module_cache__[moduleId];
13+
if (cachedModule !== undefined) {
14+
return cachedModule.exports;
15+
}
16+
// Create a new module (and put it into the cache)
17+
var module = (__webpack_module_cache__[moduleId] = {
18+
exports: {}
19+
});
20+
// Execute the module function
21+
__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
22+
23+
// Return the exports of the module
24+
return module.exports;
25+
26+
}
27+
28+
/************************************************************************/
29+
// webpack/runtime/rspack_version
30+
(() => {
31+
__webpack_require__.rv = function () {
32+
return "1.0.5";
33+
};
34+
35+
})();
36+
// webpack/runtime/rspack_unique_id
37+
(() => {
38+
__webpack_require__.ruid = "bundler=rspack@1.0.5";
39+
40+
})();
41+
/************************************************************************/
42+
43+
console.log('Hello, world!');
44+
45+
})()
46+
;

test/index.spec.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
const test = require('ava');
22
const fs = require('fs');
3+
const path = require('path');
34
const { rspack } = require('@rspack/core');
45
const { JSDOM } = require('jsdom');
56

@@ -9,8 +10,10 @@ function buildRspackConfig(entry = './test/src/index.js') {
910
return {
1011
entry,
1112
output: {
12-
filename: 'bundle.js',
13-
path: __dirname + '/test/dist'
13+
path: path.resolve(__dirname, 'dist'),
14+
},
15+
experiments: {
16+
css: false,
1417
},
1518
module: {
1619
rules: [
@@ -21,10 +24,14 @@ function buildRspackConfig(entry = './test/src/index.js') {
2124
}
2225
]
2326
},
27+
optimization: {
28+
minimize: false,
29+
},
2430
plugins: [
2531
new rspack.HtmlRspackPlugin({
2632
template: './test/src/index.html'
2733
}),
34+
new rspack.CssExtractRspackPlugin(),
2835
new HTMLInlineRspackPlugin()
2936
]
3037
}
@@ -47,7 +54,7 @@ test.before(async t => {
4754
});
4855

4956
test('CSS should be inlined into HTML', t => {
50-
const htmlContent = fs.readFileSync(__dirname + '/test/dist/index.html', 'utf-8');
57+
const htmlContent = fs.readFileSync(__dirname + '/dist/index.html', 'utf-8');
5158
const dom = new JSDOM(htmlContent);
5259
const styleTags = dom.window.document.querySelectorAll('style');
5360

test/src/style.css

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
body {
1+
h1 {
22
background-color: red;
33
}

test/test/dist/bundle.js

Lines changed: 0 additions & 1 deletion
This file was deleted.

0 commit comments

Comments
 (0)