@lynx-js/css-extract-webpack-plugin 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,58 @@
1
+ # @lynx-js/css-extract-webpack-plugin
2
+
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 1abf8f0: Use compilation hash for `css.hot-update.json` to avoid cache.
8
+
9
+ ### Patch Changes
10
+
11
+ - 1abf8f0: Set the default `targetSdkVersion` to 3.2.
12
+
13
+ ## 0.4.1
14
+
15
+ ### Patch Changes
16
+
17
+ - ad49fb1: Support CSS HMR for ReactLynx
18
+
19
+ ## 0.4.0
20
+
21
+ ### Minor Changes
22
+
23
+ - a217b02: **BREAKING CHANGE**: Change the format of scoped CSS.
24
+
25
+ ```diff
26
+ - @file "<file-key>" {
27
+ - <content>
28
+ - }
29
+ - @cssId <css-id> "<file-key>" {}
30
+ + @cssId "<css-id>" "<file-key>" {
31
+ + <content>
32
+ + }
33
+ ```
34
+
35
+ ### Patch Changes
36
+
37
+ - 0d3b44c: Support `@lynx-js/template-webpack-plugin` v0.6.0.
38
+
39
+ ## 0.3.0
40
+
41
+ ### Minor Changes
42
+
43
+ - 587a782: **BREAKING CHANGE**: Requires `@lynx-js/template-webpack-plugin` v0.5.0
44
+
45
+ ### Patch Changes
46
+
47
+ - ec189ad: Fix crash when css-loader failed.
48
+ - 5099d89: Support `common` in query.
49
+
50
+ ## 0.0.6
51
+
52
+ ### Patch Changes
53
+
54
+ - 7f8a4fe: Support Rspack v1.1.0.
55
+ - Updated dependencies [84e49f5]
56
+ - Updated dependencies [f1ddb5a]
57
+ - Updated dependencies [d05e60b]
58
+ - @lynx-js/template-webpack-plugin@0.1.0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ <h2 align="center">@lynx-js/css-extract-webpack-plugin</h2>
2
+
3
+ This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS.
@@ -0,0 +1,90 @@
1
+ import type { Compiler, CssExtractRspackPluginOptions as ExternalCssExtractRspackPluginOptions } from '@rspack/core';
2
+ import { LynxTemplatePlugin } from '@lynx-js/template-webpack-plugin';
3
+ /**
4
+ * The options for {@link @lynx-js/webpack/css-extract-webpack-plugin#CssExtractRspackPlugin}
5
+ *
6
+ * @public
7
+ */
8
+ interface CssExtractRspackPluginOptions extends ExternalCssExtractRspackPluginOptions {
9
+ /**
10
+ * {@inheritdoc @lynx-js/template-webpack-plugin#LynxTemplatePluginOptions.enableRemoveCSSScope}
11
+ */
12
+ enableRemoveCSSScope: boolean;
13
+ /**
14
+ * {@inheritdoc @lynx-js/template-webpack-plugin#LynxTemplatePluginOptions.enableCSSSelector}
15
+ */
16
+ enableCSSSelector: boolean;
17
+ /**
18
+ * {@inheritdoc @lynx-js/template-webpack-plugin#LynxTemplatePluginOptions.targetSdkVersion}
19
+ */
20
+ targetSdkVersion: string;
21
+ /**
22
+ * plugins passed to parser
23
+ */
24
+ cssPlugins: Parameters<typeof LynxTemplatePlugin.convertCSSChunksToMap>[1];
25
+ }
26
+ /**
27
+ * @public
28
+ *
29
+ * CssExtractRspackPlugin is the CSS extract plugin for Lynx.
30
+ * It works just like the {@link https://www.rspack.dev/plugins/rspack/css-extract-rspack-plugin.html | CssExtractRspackPlugin} in Web.
31
+ *
32
+ * @example
33
+ * ```js
34
+ * import { CssExtractRspackPlugin } from '@lynx-js/css-extract-webpack-plugin'
35
+ * export default {
36
+ * plugins: [new CssExtractRspackPlugin()],
37
+ * module: {
38
+ * rules: [
39
+ * {
40
+ * test: /\.css$/,
41
+ * uses: [CssExtractRspackPlugin.loader, 'css-loader'],
42
+ * },
43
+ * ],
44
+ * },
45
+ * }
46
+ * ```
47
+ */
48
+ declare class CssExtractRspackPlugin {
49
+ private readonly options?;
50
+ constructor(options?: CssExtractRspackPluginOptions | undefined);
51
+ /**
52
+ * The loader to extract CSS.
53
+ *
54
+ * @remarks
55
+ * It should be used with the {@link https://github.com/webpack-contrib/css-loader | 'css-loader'}.
56
+ *
57
+ * @example
58
+ *
59
+ * ```js
60
+ * import { CssExtractRspackPlugin } from '@lynx-js/css-extract-webpack-plugin'
61
+ * export default {
62
+ * plugins: [new CssExtractRspackPlugin()],
63
+ * module: {
64
+ * rules: [
65
+ * {
66
+ * test: /\.css$/,
67
+ * uses: [CssExtractRspackPlugin.loader, 'css-loader'],
68
+ * },
69
+ * ],
70
+ * },
71
+ * }
72
+ * ```
73
+ *
74
+ * @public
75
+ */
76
+ static loader: string;
77
+ /**
78
+ * `defaultOptions` is the default options that the {@link CssExtractRspackPlugin} uses.
79
+ *
80
+ * @public
81
+ */
82
+ static defaultOptions: Readonly<CssExtractRspackPluginOptions>;
83
+ /**
84
+ * The entry point of a webpack plugin.
85
+ * @param compiler - the webpack compiler
86
+ */
87
+ apply(compiler: Compiler): void;
88
+ }
89
+ export { CssExtractRspackPlugin };
90
+ export type { CssExtractRspackPluginOptions };
@@ -0,0 +1,180 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { createRequire } from 'node:module';
5
+ import { LynxEncodePlugin, LynxTemplatePlugin, } from '@lynx-js/template-webpack-plugin';
6
+ const require = createRequire(import.meta.url);
7
+ /**
8
+ * @public
9
+ *
10
+ * CssExtractRspackPlugin is the CSS extract plugin for Lynx.
11
+ * It works just like the {@link https://www.rspack.dev/plugins/rspack/css-extract-rspack-plugin.html | CssExtractRspackPlugin} in Web.
12
+ *
13
+ * @example
14
+ * ```js
15
+ * import { CssExtractRspackPlugin } from '@lynx-js/css-extract-webpack-plugin'
16
+ * export default {
17
+ * plugins: [new CssExtractRspackPlugin()],
18
+ * module: {
19
+ * rules: [
20
+ * {
21
+ * test: /\.css$/,
22
+ * uses: [CssExtractRspackPlugin.loader, 'css-loader'],
23
+ * },
24
+ * ],
25
+ * },
26
+ * }
27
+ * ```
28
+ */
29
+ class CssExtractRspackPlugin {
30
+ constructor(options) {
31
+ this.options = options;
32
+ }
33
+ // TODO: implement a custom loader for scoped CSS.
34
+ /**
35
+ * The loader to extract CSS.
36
+ *
37
+ * @remarks
38
+ * It should be used with the {@link https://github.com/webpack-contrib/css-loader | 'css-loader'}.
39
+ *
40
+ * @example
41
+ *
42
+ * ```js
43
+ * import { CssExtractRspackPlugin } from '@lynx-js/css-extract-webpack-plugin'
44
+ * export default {
45
+ * plugins: [new CssExtractRspackPlugin()],
46
+ * module: {
47
+ * rules: [
48
+ * {
49
+ * test: /\.css$/,
50
+ * uses: [CssExtractRspackPlugin.loader, 'css-loader'],
51
+ * },
52
+ * ],
53
+ * },
54
+ * }
55
+ * ```
56
+ *
57
+ * @public
58
+ */
59
+ static { this.loader = require.resolve('./rspack-loader.js'); }
60
+ /**
61
+ * `defaultOptions` is the default options that the {@link CssExtractRspackPlugin} uses.
62
+ *
63
+ * @public
64
+ */
65
+ static { this.defaultOptions = Object
66
+ .freeze({
67
+ enableRemoveCSSScope: false,
68
+ enableCSSSelector: true,
69
+ // TODO: version
70
+ targetSdkVersion: '3.2',
71
+ filename: '[name].css',
72
+ cssPlugins: [],
73
+ }); }
74
+ /**
75
+ * The entry point of a webpack plugin.
76
+ * @param compiler - the webpack compiler
77
+ */
78
+ apply(compiler) {
79
+ new CssExtractRspackPluginImpl(compiler, Object.assign({}, CssExtractRspackPlugin.defaultOptions, this.options));
80
+ }
81
+ }
82
+ export { CssExtractRspackPlugin };
83
+ class CssExtractRspackPluginImpl {
84
+ constructor(compiler, options) {
85
+ this.options = options;
86
+ this.name = 'CssExtractRspackPlugin';
87
+ this.hash = null;
88
+ new compiler.webpack.CssExtractRspackPlugin({
89
+ filename: options.filename ?? '[name].css',
90
+ chunkFilename: options.chunkFilename ?? '',
91
+ ignoreOrder: options.ignoreOrder ?? false,
92
+ insert: options.insert ?? '',
93
+ attributes: options.attributes ?? {},
94
+ linkType: options.linkType ?? '',
95
+ runtime: options.runtime ?? false,
96
+ }).apply(compiler);
97
+ compiler.hooks.thisCompilation.tap(this.name, (compilation) => {
98
+ if (compiler.options.mode === 'development'
99
+ || process.env['NODE_ENV'] === 'development') {
100
+ // We require publicPath to get css.hot-update.json
101
+ compilation.hooks.additionalTreeRuntimeRequirements.tap(this.name, (_, set) => {
102
+ set.add(compiler.webpack.RuntimeGlobals.publicPath);
103
+ });
104
+ compilation.hooks.runtimeModule.tap(this.name, (runtimeModule, chunk) => {
105
+ if (runtimeModule.name === 'require_chunk_loading') {
106
+ const { path } = compilation.getPathWithInfo(options.filename ?? '[name].css',
107
+ // Rspack does not pass JsChunk to Rust.
108
+ // See: https://github.com/web-infra-dev/rspack/blob/73c31abcb78472eb5a3d93e4ece19d9f106727a6/crates/rspack_binding_values/src/path_data.rs#L62
109
+ { filename: chunk.name });
110
+ this.#overrideChunkLoadingRuntimeModule(compiler, runtimeModule, path.replace('.css', `${this.hash ? `.${this.hash}` : ''}.css.hot-update.json`));
111
+ }
112
+ });
113
+ compilation.hooks.processAssets.tapPromise({
114
+ name: this.name,
115
+ stage: 300,
116
+ }, async (assets) => {
117
+ for (const [filename, source] of Object.entries(assets)) {
118
+ if (!filename.endsWith('.css')) {
119
+ continue;
120
+ }
121
+ // TODO: sourcemap
122
+ const content = source.source().toString('utf-8');
123
+ const { cssMap } = LynxTemplatePlugin.convertCSSChunksToMap([content], options.cssPlugins);
124
+ const cssDeps = Object.entries(cssMap).reduce((acc, [key, value]) => {
125
+ const importRuleNodes = value.filter((node) => node.type === 'ImportRule');
126
+ acc[key] = importRuleNodes.map(({ href }) => href);
127
+ return acc;
128
+ }, {});
129
+ const hooks = LynxTemplatePlugin.getLynxTemplatePluginHooks(
130
+ // @ts-expect-error Rspack to Webpack Compilation
131
+ compilation);
132
+ try {
133
+ const encoded = await LynxEncodePlugin.encodeCSS([content], {
134
+ targetSdkVersion: options.targetSdkVersion,
135
+ enableCSSSelector: options.enableCSSSelector,
136
+ enableRemoveCSSScope: options.enableRemoveCSSScope,
137
+ }, options.cssPlugins, hooks.encode.taps.length > 0
138
+ ? async (encodeOptions) => {
139
+ // @ts-expect-error Only CSS is needed
140
+ return await hooks.encode.promise({
141
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
142
+ encodeOptions,
143
+ });
144
+ }
145
+ : undefined);
146
+ const result = {
147
+ content: encoded.toString('base64'),
148
+ deps: cssDeps,
149
+ };
150
+ compilation.emitAsset(filename.replace('.css', `${this.hash ? `.${this.hash}` : ''}.css.hot-update.json`), new compiler.webpack.sources.RawSource(JSON.stringify(result), true));
151
+ this.hash = compilation.hash;
152
+ }
153
+ catch (error) {
154
+ if (error && typeof error === 'object' && 'error_msg' in error) {
155
+ compilation.errors.push(
156
+ // TODO: use more human-readable error message(i.e.: using sourcemap to get source code)
157
+ // or give webpack/rspack with location of bundle
158
+ new compiler.webpack.WebpackError(error.error_msg));
159
+ }
160
+ else {
161
+ compilation.errors.push(error);
162
+ }
163
+ }
164
+ }
165
+ });
166
+ }
167
+ });
168
+ }
169
+ #overrideChunkLoadingRuntimeModule(compiler, runtimeModule, filename) {
170
+ const { RuntimeGlobals } = compiler.webpack;
171
+ runtimeModule.source.source = Buffer.concat([
172
+ Buffer.from(runtimeModule.source.source),
173
+ // lynxCssFileName
174
+ Buffer.from(`
175
+ ${RuntimeGlobals.require}.lynxCssFileName = ${filename ? JSON.stringify(filename) : 'null'};
176
+ `),
177
+ ]);
178
+ }
179
+ }
180
+ //# sourceMappingURL=CssExtractRspackPlugin.js.map
@@ -0,0 +1,74 @@
1
+ import MiniCssExtractPlugin from 'mini-css-extract-plugin';
2
+ import type { Compiler } from 'webpack';
3
+ /**
4
+ * The options for CssExtractWebpackPlugin
5
+ *
6
+ * @public
7
+ */
8
+ interface CssExtractWebpackPluginOptions extends MiniCssExtractPlugin.PluginOptions {
9
+ }
10
+ /**
11
+ * @public
12
+ *
13
+ * CssExtractWebpackPlugin is the CSS extract plugin for Lynx.
14
+ * It works just like the {@link https://github.com/webpack-contrib/mini-css-extract-plugin | MiniCssExtractPlugin} in Web.
15
+ *
16
+ * @example
17
+ * ```js
18
+ * import { CssExtractWebpackPlugin } from '@lynx-js/css-extract-webpack-plugin'
19
+ * export default {
20
+ * plugins: [new CssExtractWebpackPlugin()],
21
+ * module: {
22
+ * rules: [
23
+ * {
24
+ * test: /\.css$/,
25
+ * uses: [CssExtractWebpackPlugin.loader, 'css-loader'],
26
+ * },
27
+ * ],
28
+ * },
29
+ * }
30
+ * ```
31
+ */
32
+ declare class CssExtractWebpackPlugin {
33
+ private readonly options?;
34
+ constructor(options?: CssExtractWebpackPluginOptions | undefined);
35
+ /**
36
+ * The loader to extract CSS.
37
+ *
38
+ * @remarks
39
+ * It should be used with the {@link https://github.com/webpack-contrib/css-loader | 'css-loader'}.
40
+ *
41
+ * @example
42
+ *
43
+ * ```js
44
+ * import { CssExtractWebpackPlugin } from '@lynx-js/css-extract-webpack-plugin'
45
+ * export default {
46
+ * plugins: [new CssExtractWebpackPlugin()],
47
+ * module: {
48
+ * rules: [
49
+ * {
50
+ * test: /\.css$/,
51
+ * uses: [CssExtractWebpackPlugin.loader, 'css-loader'],
52
+ * },
53
+ * ],
54
+ * },
55
+ * }
56
+ * ```
57
+ *
58
+ * @public
59
+ */
60
+ static loader: string;
61
+ /**
62
+ * `defaultOptions` is the default options that the {@link CssExtractWebpackPlugin} uses.
63
+ *
64
+ * @public
65
+ */
66
+ static defaultOptions: Readonly<Required<CssExtractWebpackPluginOptions>>;
67
+ /**
68
+ * The entry point of a webpack plugin.
69
+ * @param compiler - the webpack compiler
70
+ */
71
+ apply(compiler: Compiler): void;
72
+ }
73
+ export { CssExtractWebpackPlugin };
74
+ export type { CssExtractWebpackPluginOptions };
@@ -0,0 +1,99 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { createRequire } from 'node:module';
5
+ import MiniCssExtractPlugin from 'mini-css-extract-plugin';
6
+ const require = createRequire(import.meta.url);
7
+ /**
8
+ * @public
9
+ *
10
+ * CssExtractWebpackPlugin is the CSS extract plugin for Lynx.
11
+ * It works just like the {@link https://github.com/webpack-contrib/mini-css-extract-plugin | MiniCssExtractPlugin} in Web.
12
+ *
13
+ * @example
14
+ * ```js
15
+ * import { CssExtractWebpackPlugin } from '@lynx-js/css-extract-webpack-plugin'
16
+ * export default {
17
+ * plugins: [new CssExtractWebpackPlugin()],
18
+ * module: {
19
+ * rules: [
20
+ * {
21
+ * test: /\.css$/,
22
+ * uses: [CssExtractWebpackPlugin.loader, 'css-loader'],
23
+ * },
24
+ * ],
25
+ * },
26
+ * }
27
+ * ```
28
+ */
29
+ class CssExtractWebpackPlugin {
30
+ constructor(options) {
31
+ this.options = options;
32
+ }
33
+ /**
34
+ * The loader to extract CSS.
35
+ *
36
+ * @remarks
37
+ * It should be used with the {@link https://github.com/webpack-contrib/css-loader | 'css-loader'}.
38
+ *
39
+ * @example
40
+ *
41
+ * ```js
42
+ * import { CssExtractWebpackPlugin } from '@lynx-js/css-extract-webpack-plugin'
43
+ * export default {
44
+ * plugins: [new CssExtractWebpackPlugin()],
45
+ * module: {
46
+ * rules: [
47
+ * {
48
+ * test: /\.css$/,
49
+ * uses: [CssExtractWebpackPlugin.loader, 'css-loader'],
50
+ * },
51
+ * ],
52
+ * },
53
+ * }
54
+ * ```
55
+ *
56
+ * @public
57
+ */
58
+ static { this.loader = require.resolve('./loader.js'); }
59
+ /**
60
+ * `defaultOptions` is the default options that the {@link CssExtractWebpackPlugin} uses.
61
+ *
62
+ * @public
63
+ */
64
+ static { this.defaultOptions = Object.freeze({
65
+ filename: '[name].css',
66
+ chunkFilename: undefined,
67
+ ignoreOrder: undefined,
68
+ insert: undefined,
69
+ attributes: undefined,
70
+ linkType: undefined,
71
+ runtime: undefined,
72
+ experimentalUseImportModule: undefined,
73
+ }); }
74
+ /**
75
+ * The entry point of a webpack plugin.
76
+ * @param compiler - the webpack compiler
77
+ */
78
+ apply(compiler) {
79
+ new CssExtractWebpackPluginImpl(compiler, Object.assign({}, CssExtractWebpackPlugin.defaultOptions, this.options));
80
+ }
81
+ }
82
+ export { CssExtractWebpackPlugin };
83
+ class CssExtractWebpackPluginImpl {
84
+ constructor(compiler, options) {
85
+ this.options = options;
86
+ this.name = 'CssExtractWebpackPlugin';
87
+ new MiniCssExtractPlugin({
88
+ filename: options.filename,
89
+ chunkFilename: options.chunkFilename,
90
+ ignoreOrder: options.ignoreOrder,
91
+ insert: options.insert,
92
+ attributes: options.attributes,
93
+ linkType: options.linkType,
94
+ runtime: options.runtime,
95
+ experimentalUseImportModule: options.experimentalUseImportModule,
96
+ }).apply(compiler);
97
+ }
98
+ }
99
+ //# sourceMappingURL=CssExtractWebpackPlugin.js.map
package/lib/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS and CSSId.
5
+ */
6
+ export { CssExtractWebpackPlugin } from './CssExtractWebpackPlugin.js';
7
+ export type { CssExtractWebpackPluginOptions } from './CssExtractWebpackPlugin.js';
8
+ export type { LoaderOptions } from './loader.js';
9
+ export type { LoaderOptions as CssExtractRspackLoaderOptions } from './loader.js';
10
+ export { CssExtractRspackPlugin } from './CssExtractRspackPlugin.js';
11
+ export type { CssExtractRspackPluginOptions } from './CssExtractRspackPlugin.js';
package/lib/index.js ADDED
@@ -0,0 +1,11 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ /**
5
+ * @packageDocumentation
6
+ *
7
+ * This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS and CSSId.
8
+ */
9
+ export { CssExtractWebpackPlugin } from './CssExtractWebpackPlugin.js';
10
+ export { CssExtractRspackPlugin } from './CssExtractRspackPlugin.js';
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,47 @@
1
+ import type { LoaderContext } from 'webpack';
2
+ /**
3
+ * The options of CSS extract loader.
4
+ *
5
+ * @public
6
+ */
7
+ export interface LoaderOptions {
8
+ /**
9
+ * The same as {@link https://github.com/webpack-contrib/mini-css-extract-plugin/tree/master?tab=readme-ov-file#emit | mini-css-extract-plugin}.
10
+ * Control whether emit the CSS to filesystem.
11
+ *
12
+ * - If `true`(default), emits a file (writes a file to the filesystem).
13
+ *
14
+ * - If `false`, the plugin will extract the CSS but will not emit the file.
15
+ *
16
+ * It is often useful to disable this option for server-side packages.
17
+ *
18
+ * @defaultValue true
19
+ * @public
20
+ */
21
+ emit?: boolean;
22
+ /**
23
+ * {@inheritdoc @lynx-js/rspeedy#CssExtractRspackLoaderOptions.esModule}
24
+ */
25
+ esModule?: boolean | undefined;
26
+ /**
27
+ * The layer of the CSS execution.
28
+ *
29
+ * @remarks
30
+ *
31
+ * This should be combined with `experiments.layers`.
32
+ */
33
+ layer?: string | undefined;
34
+ }
35
+ export interface Dep {
36
+ identifier: string;
37
+ context: string | null;
38
+ content: Buffer;
39
+ media: string;
40
+ identifierIndex?: number;
41
+ supports?: string | undefined;
42
+ layer?: string | undefined;
43
+ sourceMap?: Buffer | undefined;
44
+ }
45
+ export declare function load(this: LoaderContext<LoaderOptions>, request: string, addDependencies: (deps: Dep[]) => void): Promise<string>;
46
+ export declare function pitch(this: LoaderContext<LoaderOptions>, request: string): Promise<string | undefined>;
47
+ export default function loader(this: LoaderContext<LoaderOptions>, content: string): string | undefined;
package/lib/loader.js ADDED
@@ -0,0 +1,234 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import MiniCssExtractPlugin from 'mini-css-extract-plugin';
7
+ import { extractPathFromIdentifier, stringifyRequest } from './util.js';
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ const BASE_URI = 'webpack://';
10
+ export async function load(request, addDependencies) {
11
+ /** TODO: schema */
12
+ const options = this.getOptions();
13
+ const emit = options.emit ?? true;
14
+ const esModule = options.esModule ?? true;
15
+ const moduleExports = await new Promise((resolve, reject) => {
16
+ this.importModule(`${this.resourcePath}.webpack[javascript/auto]!=!!!${request}`, {
17
+ baseUri: `${BASE_URI}/`,
18
+ layer: options.layer,
19
+ }, (err, exports) => {
20
+ if (err) {
21
+ return reject(err);
22
+ }
23
+ return resolve(exports);
24
+ });
25
+ });
26
+ let locals;
27
+ if (isNamedExports(moduleExports)) {
28
+ Object.keys(moduleExports).forEach((key) => {
29
+ if (key !== 'default') {
30
+ if (!locals) {
31
+ locals = {};
32
+ }
33
+ locals[key] = moduleExports[key];
34
+ }
35
+ });
36
+ }
37
+ else {
38
+ locals =
39
+ (isCJSExports(moduleExports) ? moduleExports : moduleExports.default)
40
+ ?.locals;
41
+ }
42
+ let dependencies;
43
+ const exportContent = isCJSExports(moduleExports)
44
+ ? moduleExports
45
+ : moduleExports.default;
46
+ const { cssId: rawCssId } = parseQuery(this.resourceQuery);
47
+ const cssId = rawCssId ?? '';
48
+ const identifierCountMap = new Map();
49
+ if (Array.isArray(exportContent)) {
50
+ dependencies = exportContent.map(([identifier, content, media, sourceMap, supports, layer]) => {
51
+ const count = identifierCountMap.get(identifier) ?? 0;
52
+ const rawResourcePath = extractPathFromIdentifier(identifier, true);
53
+ const [resourcePath, resourceQuery] = rawResourcePath.split('?');
54
+ const params = new URLSearchParams(resourceQuery ? `?${resourceQuery}` : '');
55
+ if (params.get('cssId') === null) {
56
+ params.set('cssId', cssId);
57
+ }
58
+ const filePath = path.relative(this.rootContext, extractPathFromIdentifier(identifier));
59
+ identifierCountMap.set(identifier, count + 1);
60
+ return {
61
+ identifier: identifier.replace(rawResourcePath, `${resourcePath}?${params.toString()}`),
62
+ context: this.rootContext,
63
+ content: Buffer.from(cssId
64
+ && (params.get('common') === null
65
+ || params.get('common') === 'false')
66
+ /**
67
+ * Given the following source code:
68
+ *
69
+ * ```css foo.css?cssId=1001
70
+ * @import 'bar.css'
71
+ * .foo {
72
+ * color: red;
73
+ * }
74
+ * ```
75
+ *
76
+ * ```css bar.css
77
+ * .bar {
78
+ * color: blue;
79
+ * }
80
+ * ```
81
+ *
82
+ * The output should be:
83
+ *
84
+ * ```css
85
+ * @cssId "1001" "bar.css" {
86
+ * .bar {
87
+ * color: blue;
88
+ * }
89
+ * }
90
+ * @cssId "1001" "foo.css" {
91
+ * .foo {
92
+ * color: red;
93
+ * }
94
+ * }
95
+ * ```
96
+ */
97
+ ? `\
98
+ @cssId "${cssId}" "${filePath}" {
99
+ ${content}
100
+ }
101
+ `
102
+ : content),
103
+ media,
104
+ supports,
105
+ layer,
106
+ identifierIndex: count,
107
+ sourceMap: sourceMap
108
+ ? Buffer.from(JSON.stringify(sourceMap))
109
+ : undefined,
110
+ };
111
+ });
112
+ addDependencies(dependencies);
113
+ }
114
+ else {
115
+ dependencies = [[null, exportContent]];
116
+ }
117
+ const result = (function makeResult() {
118
+ if (locals) {
119
+ if (isNamedExports(moduleExports)) {
120
+ const identifiers = Array.from((function* generateIdentifiers() {
121
+ let identifierId = 0;
122
+ for (const key of Object.keys(locals)) {
123
+ identifierId += 1;
124
+ yield [`_${identifierId.toString(16)}`, key];
125
+ }
126
+ })());
127
+ const localsString = identifiers
128
+ .map(
129
+ // TODO: support function locals
130
+ ([id, key]) => `\nvar ${id} = ${JSON.stringify(locals[key])};`)
131
+ .join('');
132
+ const exportsString = `export { ${identifiers
133
+ .map(([id, key]) => `${id} as ${JSON.stringify(key)}`)
134
+ .join(', ')} }`;
135
+ return `${localsString}\n${exportsString}\n`;
136
+ }
137
+ return `\n${esModule ? 'export default' : 'module.exports = '} ${JSON.stringify(locals)};`;
138
+ }
139
+ else if (esModule) {
140
+ return '\nexport {};';
141
+ }
142
+ return '';
143
+ })();
144
+ let resultSource = `// extracted by ${MiniCssExtractPlugin.pluginName}`;
145
+ // only attempt hot reloading if the css is actually used for something other than hash values
146
+ resultSource += this.hot && emit
147
+ ? hotLoader(result, {
148
+ loaderContext: this,
149
+ options,
150
+ locals,
151
+ cssId,
152
+ })
153
+ : result;
154
+ return resultSource;
155
+ }
156
+ export async function pitch(request) {
157
+ if (this._compiler?.options?.experiments?.css
158
+ && this._module
159
+ && (this._module.type === 'css'
160
+ || this._module.type === 'css/auto'
161
+ || this._module.type === 'css/global'
162
+ || this._module.type === 'css/module')) {
163
+ this.emitWarning(new Error('You can\'t use `experiments.css` (`experiments.futureDefaults` enable built-in CSS support by default) and `@lynx-js/css-extract-webpack-plugin` together, please set `experiments.css` to `false` or set `{ type: "javascript/auto" }` for rules with `@lynx-js/css-extract-webpack-plugin` in your webpack config (now `@lynx-js/css-extract-webpack-plugin` does nothing).'));
164
+ return;
165
+ }
166
+ /** TODO: schema */
167
+ const options = this.getOptions();
168
+ const emit = options.emit ?? true;
169
+ const addDependencies = (dependencies) => {
170
+ const { webpack } = this._compiler;
171
+ if (!Array.isArray(dependencies) && dependencies !== null) {
172
+ throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(dependencies)}`);
173
+ }
174
+ const identifierCountMap = new Map();
175
+ for (const dependency of dependencies) {
176
+ if (!('identifier' in dependency) || !emit) {
177
+ continue;
178
+ }
179
+ const CssDependency = MiniCssExtractPlugin.getCssDependency(webpack);
180
+ const count = identifierCountMap.get(dependency.identifier) ?? 0;
181
+ this._module.addDependency(new CssDependency(dependency, dependency.context, count));
182
+ identifierCountMap.set(dependency.identifier, count + 1);
183
+ }
184
+ };
185
+ return await load.call(this, request, addDependencies);
186
+ }
187
+ export default function loader(content) {
188
+ if (this._compiler?.options?.experiments?.css
189
+ && this._module
190
+ && (this._module.type === 'css'
191
+ || this._module.type === 'css/auto'
192
+ || this._module.type === 'css/global'
193
+ || this._module.type === 'css/module')) {
194
+ return content;
195
+ }
196
+ return;
197
+ }
198
+ function hotLoader(content, context) {
199
+ const localsJsonString = JSON.stringify(JSON.stringify(context.locals));
200
+ return `${content}
201
+ if (module.hot) {
202
+ (function() {
203
+ var localsJsonString = ${localsJsonString};
204
+ // ${Date.now()}
205
+ var cssReload = require(${stringifyRequest(context.loaderContext, path.resolve(__dirname, '../runtime/hotModuleReplacement.cjs'))})(module.id, ${JSON.stringify(context.options)}, "${context.cssId ?? '0'}");
206
+ // only invalidate when locals change
207
+ if (
208
+ module.hot.data &&
209
+ module.hot.data.value &&
210
+ module.hot.data.value !== localsJsonString
211
+ ) {
212
+ module.hot.invalidate();
213
+ } else {
214
+ module.hot.accept();
215
+ }
216
+ module.hot.dispose(function(data) {
217
+ data.value = localsJsonString;
218
+ cssReload();
219
+ });
220
+ })();
221
+ }`;
222
+ }
223
+ function isCJSExports(exports) {
224
+ return !exports.__esModule;
225
+ }
226
+ function isNamedExports(exports) {
227
+ return !isCJSExports(exports)
228
+ && (!exports.default || !('locals' in exports.default));
229
+ }
230
+ function parseQuery(query) {
231
+ const params = new URLSearchParams(query);
232
+ return Object.fromEntries(params);
233
+ }
234
+ //# sourceMappingURL=loader.js.map
@@ -0,0 +1,5 @@
1
+ import type { LoaderContext } from '@rspack/core';
2
+ import type { LoaderOptions } from './loader.js';
3
+ export declare function pitch(this: LoaderContext<LoaderOptions>, request: string,
4
+ /** previousRequest */ _: string, data: Record<string, unknown>): Promise<void>;
5
+ export default function loader(this: LoaderContext<LoaderOptions>, content: string): string | undefined;
@@ -0,0 +1,43 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { load } from './loader.js';
5
+ export async function pitch(request,
6
+ /** previousRequest */ _, data) {
7
+ if (this._compiler?.options?.experiments?.css) {
8
+ this.emitWarning(new Error('You can\'t use `experiments.css` (`experiments.futureDefaults` enable built-in CSS support by default) and `@lynx-js/css-extract-webpack-plugin` together, please set `experiments.css` to `false` or set `{ type: "javascript/auto" }` for rules with `@lynx-js/css-extract-webpack-plugin` in your webpack config (now `@lynx-js/css-extract-webpack-plugin` does nothing).'));
9
+ return;
10
+ }
11
+ const callback = this.async();
12
+ // See: https://github.com/web-infra-dev/rspack/pull/7878
13
+ const parseMeta = this.__internal__parseMeta;
14
+ try {
15
+ // Rspack does not return error in `importModule`.
16
+ // So the `load` function may crash.
17
+ // We make an temporary try-catch here.
18
+ // See: https://github.com/web-infra-dev/rspack/issues/8536
19
+ const resultSource = await load.call(
20
+ // @ts-expect-error webpack & rspack loaderContext
21
+ this, request, addDependencies.bind(this));
22
+ callback(null, resultSource, undefined, data);
23
+ }
24
+ catch (error) {
25
+ callback(error);
26
+ }
27
+ function addDependencies(dependencies) {
28
+ parseMeta[this._compiler.webpack.CssExtractRspackPlugin.pluginName] = JSON
29
+ .stringify(dependencies
30
+ .map(dep => ({
31
+ ...dep,
32
+ content: dep.content.toString('utf-8'),
33
+ sourceMap: dep.sourceMap?.toString('utf-8'),
34
+ })));
35
+ }
36
+ }
37
+ export default function loader(content) {
38
+ if (this._compiler?.options?.experiments?.css) {
39
+ return content;
40
+ }
41
+ return;
42
+ }
43
+ //# sourceMappingURL=rspack-loader.js.map
package/lib/util.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { LoaderOptions } from 'mini-css-extract-plugin';
2
+ import type { LoaderContext } from 'webpack';
3
+ export declare function isAbsolutePath(str: string): boolean;
4
+ export declare function isRelativePath(str: string): boolean;
5
+ export declare function stringifyRequest(loaderContext: LoaderContext<LoaderOptions>, request: string): string;
6
+ /**
7
+ * Extract file path from the identifier.
8
+ *
9
+ * @example
10
+ *
11
+ * Given identifier `css-loader/index.js??ruleSet[1].rules[1].use[1]!./src/baz.css`,
12
+ * result in `./src/baz.css`
13
+ *
14
+ * Given identifier `css-loader/index.js??ruleSet[1].rules[1].use[1]!./src/baz.css?cssId=123`, and the withPathQuery is false
15
+ * result in `./src/baz.css`
16
+ *
17
+ * Given identifier `css-loader/index.js??ruleSet[1].rules[1].use[1]!./src/baz.css?cssId=123`, and the withPathQuery is true
18
+ * result in `./src/baz.css?cssId=123`
19
+ *
20
+ * @param identifier - The Webpack/Rspack identifier
21
+ * @param withPathQuery - Whether keep the query(e.g: ?xxx=xx) in the path
22
+ * @returns The resourcePath of the identifier.
23
+ */
24
+ export declare function extractPathFromIdentifier(identifier: string, withPathQuery?: boolean): string | undefined;
package/lib/util.js ADDED
@@ -0,0 +1,65 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import path from 'node:path';
5
+ export function isAbsolutePath(str) {
6
+ return path.posix.isAbsolute(str) || path.win32.isAbsolute(str);
7
+ }
8
+ const RELATIVE_PATH_REGEXP = /^\.\.?[/\\]/;
9
+ export function isRelativePath(str) {
10
+ return RELATIVE_PATH_REGEXP.test(str);
11
+ }
12
+ export function stringifyRequest(loaderContext, request) {
13
+ if (typeof loaderContext.utils !== 'undefined'
14
+ && typeof loaderContext.utils.contextify === 'function') {
15
+ return JSON.stringify(loaderContext.utils.contextify(loaderContext.context || loaderContext.rootContext, request));
16
+ }
17
+ const splitted = request.split('!');
18
+ const { context } = loaderContext;
19
+ return JSON.stringify(splitted
20
+ .map((part) => {
21
+ // First, separate singlePath from query, because the query might contain paths again
22
+ const splittedPart = /^(.*?)(\?.*)/.exec(part);
23
+ const query = splittedPart ? splittedPart[2] : '';
24
+ let singlePath = splittedPart ? splittedPart[1] : part;
25
+ if (isAbsolutePath(singlePath) && context) {
26
+ singlePath = path.relative(context, singlePath);
27
+ if (isAbsolutePath(singlePath)) {
28
+ // If singlePath still matches an absolute path, singlePath was on a different drive than context.
29
+ // In this case, we leave the path platform-specific without replacing any separators.
30
+ // @see https://github.com/webpack/loader-utils/pull/14
31
+ return singlePath + query;
32
+ }
33
+ if (isRelativePath(singlePath) === false) {
34
+ // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules).
35
+ singlePath = `./${singlePath}`;
36
+ }
37
+ }
38
+ return singlePath.replace(/\\/g, '/') + query;
39
+ })
40
+ .join('!'));
41
+ }
42
+ /**
43
+ * Extract file path from the identifier.
44
+ *
45
+ * @example
46
+ *
47
+ * Given identifier `css-loader/index.js??ruleSet[1].rules[1].use[1]!./src/baz.css`,
48
+ * result in `./src/baz.css`
49
+ *
50
+ * Given identifier `css-loader/index.js??ruleSet[1].rules[1].use[1]!./src/baz.css?cssId=123`, and the withPathQuery is false
51
+ * result in `./src/baz.css`
52
+ *
53
+ * Given identifier `css-loader/index.js??ruleSet[1].rules[1].use[1]!./src/baz.css?cssId=123`, and the withPathQuery is true
54
+ * result in `./src/baz.css?cssId=123`
55
+ *
56
+ * @param identifier - The Webpack/Rspack identifier
57
+ * @param withPathQuery - Whether keep the query(e.g: ?xxx=xx) in the path
58
+ * @returns The resourcePath of the identifier.
59
+ */
60
+ export function extractPathFromIdentifier(identifier, withPathQuery = false) {
61
+ const regex = withPathQuery ? /!([^!]+)$/ : /!([^!?]+)(?:\?[^!]*)?$/;
62
+ const matches = regex.exec(identifier);
63
+ return matches?.[1];
64
+ }
65
+ //# sourceMappingURL=util.js.map
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@lynx-js/css-extract-webpack-plugin",
3
+ "version": "0.5.0",
4
+ "description": "This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS.",
5
+ "keywords": [
6
+ "webpack",
7
+ "Lynx"
8
+ ],
9
+ "license": "Apache-2.0",
10
+ "author": {
11
+ "name": "Qingyu Wang",
12
+ "email": "colinwang.0616@gmail.com"
13
+ },
14
+ "type": "module",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./lib/index.d.ts",
18
+ "import": "./lib/index.js"
19
+ },
20
+ "./runtime/hotModuleReplacement.cjs": {
21
+ "type": "./runtime/hotModuleReplacement.d.cts",
22
+ "default": "./runtime/hotModuleReplacement.cjs"
23
+ },
24
+ "./runtime/hotModuleReplacement.lepus.cjs": {
25
+ "type": "./runtime/hotModuleReplacement.lepus.d.cts",
26
+ "default": "./runtime/hotModuleReplacement.lepus.cjs"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "types": "./lib/index.d.ts",
31
+ "files": [
32
+ "lib",
33
+ "!lib/**/*.js.map",
34
+ "runtime",
35
+ "CHANGELOG.md",
36
+ "README.md"
37
+ ],
38
+ "dependencies": {
39
+ "mini-css-extract-plugin": "^2.9.2"
40
+ },
41
+ "devDependencies": {
42
+ "@microsoft/api-extractor": "7.51.0",
43
+ "@rspack/cli": "1.2.6",
44
+ "@rspack/core": "1.2.6",
45
+ "css-loader": "^7.1.2",
46
+ "sass-loader": "^16.0.5",
47
+ "webpack": "^5.98.0",
48
+ "@lynx-js/css-serializer": "0.1.1",
49
+ "@lynx-js/template-webpack-plugin": "0.6.3",
50
+ "@lynx-js/test-tools": "0.0.0"
51
+ },
52
+ "peerDependencies": {
53
+ "@lynx-js/template-webpack-plugin": "^0.5.0 || ^0.6.0"
54
+ },
55
+ "engines": {
56
+ "node": ">=18"
57
+ },
58
+ "scripts": {
59
+ "api-extractor": "api-extractor run --verbose",
60
+ "test": "pnpm -w run test --project webpack/css-extract"
61
+ }
62
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @param {Function} fn
3
+ * @param {number} time
4
+ * @returns {function(): void}
5
+ */
6
+ function debounce(fn, time) {
7
+ let timeout = 0;
8
+
9
+ return function debounced(...args) {
10
+ clearTimeout(timeout);
11
+
12
+ timeout = setTimeout(
13
+ () => fn.apply(this, args),
14
+ time,
15
+ );
16
+ };
17
+ }
18
+
19
+ function updateStyle(cssId = 0) {
20
+ const filename = __webpack_require__.lynxCssFileName;
21
+ if (!filename) {
22
+ throw new Error('Css Filename not found');
23
+ }
24
+
25
+ lynx.requireModuleAsync(
26
+ // lynx.requireModuleAsync has two level hash and we cannot delete
27
+ // the LynxGroup level cache here.
28
+ // Temporarily using `Date.now` to avoid being cached.
29
+ __webpack_require__.p + filename,
30
+ (err, ret) => {
31
+ if (err) {
32
+ throw new Error('Load update css file `' + filename + '` failed');
33
+ }
34
+
35
+ if (ret.content) {
36
+ lynx.getCoreContext().dispatchEvent({
37
+ type: 'lynx.hmr.css',
38
+ data: { cssId, content: ret.content, deps: ret.deps },
39
+ });
40
+ }
41
+ },
42
+ );
43
+ }
44
+
45
+ /**
46
+ * @param {string | number} moduleId
47
+ * @param {unknown} options
48
+ * @param {number=} cssId
49
+ * @returns {() => void}
50
+ */
51
+ module.exports = function update(moduleId, options, cssId) {
52
+ // TODO: should not pass cssId === ''
53
+ if (!cssId) {
54
+ cssId = 0;
55
+ }
56
+
57
+ function update() {
58
+ updateStyle(cssId);
59
+ }
60
+
61
+ return debounce(update, 50);
62
+ };
@@ -0,0 +1,7 @@
1
+ declare function update(
2
+ moduleId: string | number,
3
+ options: unknown,
4
+ cssId?: number,
5
+ ): () => void;
6
+
7
+ export = update;
@@ -0,0 +1,34 @@
1
+ function main() {
2
+ try {
3
+ lynx.getJSContext().addEventListener('lynx.hmr.css', (event) => {
4
+ try {
5
+ const { data: { cssId, content, deps } } = event;
6
+ // Update the css deps first because the css deps are updated actually.
7
+ if (Array.isArray(deps[cssId])) {
8
+ deps[cssId].forEach(depCSSId => {
9
+ lynx.getDevtool().replaceStyleSheetByIdWithBase64(
10
+ Number(depCSSId),
11
+ content,
12
+ );
13
+ });
14
+ }
15
+
16
+ lynx.getDevtool().replaceStyleSheetByIdWithBase64(
17
+ Number(cssId),
18
+ content,
19
+ );
20
+
21
+ __FlushElementTree();
22
+ } catch (error) {
23
+ // TODO: use webpack-dev-server logger
24
+ console.error(error);
25
+ }
26
+ });
27
+ } catch (error) {
28
+ // TODO: use webpack-dev-server logger
29
+ console.warn(`[HMR] no lynx.getJSContext() found, will not HMR CSS`);
30
+ console.warn(error);
31
+ }
32
+ }
33
+
34
+ main();
@@ -0,0 +1 @@
1
+ export {};