Skip to content

Commit 1d9015c

Browse files
authored
feat: add Vite support for exported web components (#13148)
This PR adds Vite support for exported web components making it possible to build and run them with Vite in development and production modes. A brief overview of the differences between Webpack and Vite implementations: **Webpack:** When there is any component marked as exported, in addition to `bundle-***.js`, Webpack will build an `export-***.js` chunk that contains `generated-flow-imports`. The Flow client will be generated by Flow as a separate script. Once an exported web component is requested, `WebComponentBootstrapHandler` is the one that is in charge of generating a bootstrap script to initialize this web component. The current Webpack implementation of `WebComponentBootstrapHandler` is based on `BootstrapHandler`. It dynamically builds an HTML bootstrap document injecting all the scripts required for the exported web component to work to the document's head. There is where it will inject the Flow client as a separate script and the `export-***.js` chunk, getting it from the chunk stats file. Eventually, the handler serializes the head of the resulting HTML document into a set of javascript instructions and sends them to the browser as a result. **Vite:** When there is any component marked as exported, Vite will build `vaadin-web-component.ts` and inject it to `web-component.html`. It is worth noting that `vaadin-web-component.ts` includes both `generated-flow-imports` and the Flow client. For Vite, the `WebComponentBootstrapHandler` logic was modified such that it instead takes `web-component.html` as an initial bootstrap document. The bootstrap document already contains the actual link to `vaadin-web-component.ts` which is injected by Vite. All the other scripts required for the exported web component to work, such as the `@Push` annotation script, the handler injects dynamically. An advantage of this approach is that it doesn't require any chunk stats so that it works pretty much the same way as `IndexHtmlRequestHandler`. Eventually, the handler serializes the head of the resulting HTML document into a set of javascript instructions and sends them to the browser as a result. Fixes #12298
1 parent 4b10fd4 commit 1d9015c

29 files changed

Lines changed: 918 additions & 21 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/server/BootstrapHandler.java‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1204,7 +1204,7 @@ private void setupPwa(Document document, BootstrapContext context) {
12041204
context.getPwaRegistry().orElse(null));
12051205
}
12061206

1207-
private Element createInlineJavaScriptElement(
1207+
protected Element createInlineJavaScriptElement(
12081208
String javaScriptContents) {
12091209
// defer makes no sense without src:
12101210
// https://developer.mozilla.org/en/docs/Web/HTML/Element/script
@@ -1213,17 +1213,17 @@ private Element createInlineJavaScriptElement(
12131213
return wrapper;
12141214
}
12151215

1216-
private static Element createJavaScriptElement(String sourceUrl,
1216+
protected static Element createJavaScriptElement(String sourceUrl,
12171217
boolean defer) {
12181218
return createJavaScriptElement(sourceUrl, defer, "text/javascript");
12191219
}
12201220

1221-
private static Element createJavaScriptModuleElement(String sourceUrl,
1221+
protected static Element createJavaScriptModuleElement(String sourceUrl,
12221222
boolean defer) {
12231223
return createJavaScriptElement(sourceUrl, defer, "module");
12241224
}
12251225

1226-
private static Element createJavaScriptElement(String sourceUrl,
1226+
protected static Element createJavaScriptElement(String sourceUrl,
12271227
boolean defer, String type) {
12281228
Element jsElement = new Element(Tag.valueOf(SCRIPT_TAG), "")
12291229
.attr("type", type).attr(DEFER_ATTRIBUTE, defer);
@@ -1233,7 +1233,7 @@ private static Element createJavaScriptElement(String sourceUrl,
12331233
return jsElement;
12341234
}
12351235

1236-
private static Element createJavaScriptElement(String sourceUrl) {
1236+
protected static Element createJavaScriptElement(String sourceUrl) {
12371237
return createJavaScriptElement(sourceUrl, true);
12381238
}
12391239

@@ -1290,7 +1290,7 @@ private void setupDocumentBody(Document document) {
12901290
"You have to enable javascript in your browser to use this web site.");
12911291
}
12921292

1293-
private Element getBootstrapScript(JsonValue initialUIDL,
1293+
protected Element getBootstrapScript(JsonValue initialUIDL,
12941294
BootstrapContext context) {
12951295
return createInlineJavaScriptElement("//<![CDATA[\n"
12961296
+ getBootstrapJS(initialUIDL, context) + "//]]>");

‎flow-server/src/main/java/com/vaadin/flow/server/communication/WebComponentBootstrapHandler.java‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,23 +29,30 @@
2929
import java.util.function.Function;
3030
import java.util.regex.Pattern;
3131

32+
import org.jsoup.Jsoup;
3233
import org.jsoup.nodes.Attribute;
34+
import org.jsoup.nodes.DataNode;
3335
import org.jsoup.nodes.Document;
3436
import org.jsoup.nodes.Element;
37+
import org.jsoup.parser.Tag;
3538

39+
import com.vaadin.experimental.FeatureFlags;
3640
import com.vaadin.flow.component.PushConfiguration;
3741
import com.vaadin.flow.component.UI;
3842
import com.vaadin.flow.component.webcomponent.WebComponentUI;
3943
import com.vaadin.flow.dom.ElementUtil;
4044
import com.vaadin.flow.internal.JsonUtils;
45+
import com.vaadin.flow.server.BootstrapException;
4146
import com.vaadin.flow.server.BootstrapHandler;
4247
import com.vaadin.flow.server.Constants;
4348
import com.vaadin.flow.server.HandlerHelper;
4449
import com.vaadin.flow.server.PwaRegistry;
4550
import com.vaadin.flow.server.VaadinRequest;
4651
import com.vaadin.flow.server.VaadinResponse;
52+
import com.vaadin.flow.server.VaadinService;
4753
import com.vaadin.flow.server.VaadinServletRequest;
4854
import com.vaadin.flow.server.VaadinSession;
55+
import com.vaadin.flow.server.frontend.FrontendUtils;
4956
import com.vaadin.flow.server.webcomponent.WebComponentConfigurationRegistry;
5057
import com.vaadin.flow.shared.ApplicationConstants;
5158

@@ -97,6 +104,48 @@ protected Optional<PwaRegistry> getPwaRegistry() {
97104

98105
private static class WebComponentBootstrapPageBuilder
99106
extends BootstrapPageBuilder {
107+
@Override
108+
public Document getBootstrapPage(BootstrapContext context) {
109+
VaadinService service = context.getSession().getService();
110+
111+
if (FeatureFlags.get(service.getContext())
112+
.isEnabled(FeatureFlags.VITE)) {
113+
try {
114+
Document document = Jsoup.parse(
115+
FrontendUtils.getWebComponentHtmlContent(service));
116+
Element head = document.head();
117+
118+
// Specify the application ID for scripts of the
119+
// web-component.html
120+
head.select("script[src]").attr("data-app-id",
121+
context.getUI().getInternals().getAppId());
122+
123+
// Add `crossorigin` to fix basic auth in Safari #6560
124+
head.select("script[src], link[href]").attr("crossorigin",
125+
"true");
126+
127+
JsonObject initialUIDL = getInitialUidl(context.getUI());
128+
129+
head.prependChild(createInlineJavaScriptElement(
130+
"window.JSCompiler_renameProperty = function(a) { return a; }"));
131+
132+
head.prependChild(getBootstrapScript(initialUIDL, context));
133+
134+
if (context.getPushMode().isEnabled()) {
135+
head.prependChild(createJavaScriptModuleElement(
136+
getPushScript(context), true));
137+
}
138+
139+
return document;
140+
} catch (IOException e) {
141+
throw new BootstrapException(
142+
"Unable to read the web-component.html file.", e);
143+
}
144+
}
145+
146+
return super.getBootstrapPage(context);
147+
}
148+
100149
@Override
101150
protected List<String> getChunkKeys(JsonObject chunks) {
102151
if (chunks.hasKey(EXPORT_CHUNK)) {
@@ -395,8 +444,9 @@ private void transferAttribute(Writer writer, String elementRef,
395444
if (attribute.getValue() == null) {
396445
writer.append("''");
397446
} else {
447+
String name = attribute.getKey();
398448
String path = attribute.getValue();
399-
if ("src".equals(attribute.getKey())) {
449+
if (name.matches("^(src|href)$")) {
400450
path = modifyPath(basePath, path);
401451
}
402452
writer.append("\"").append(path).append("\"");

‎flow-server/src/main/java/com/vaadin/flow/server/frontend/FrontendUtils.java‎

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,13 @@ public class FrontendUtils {
201201
*/
202202
public static final String BOOTSTRAP_FILE_NAME = "vaadin.ts";
203203

204+
/**
205+
* File name of the web component bootstrap file that is generated in
206+
* frontend {@link #GENERATED} folder. The bootstrap file is always executed
207+
* in an exported web component.
208+
*/
209+
public static final String WEB_COMPONENT_BOOTSTRAP_FILE_NAME = "vaadin-web-component.ts";
210+
204211
/**
205212
* File name of the feature flags file that is generated in frontend
206213
* {@link #GENERATED} folder. The feature flags file contains code to define
@@ -214,6 +221,11 @@ public class FrontendUtils {
214221
*/
215222
public static final String INDEX_HTML = "index.html";
216223

224+
/**
225+
* File name of the web-component.html in client side.
226+
*/
227+
public static final String WEB_COMPONENT_HTML = "web-component.html";
228+
217229
/**
218230
* File name of the index.ts in client side.
219231
*/
@@ -459,11 +471,13 @@ public static void clearCachedStatsContent(VaadinService service) {
459471

460472
/**
461473
* Gets the content of the <code>frontend/index.html</code> file which is
462-
* served by webpack-dev-server in dev-mode and read from classpath in
463-
* production mode. NOTE: In dev mode, the file content file is fetched via
464-
* webpack http request. So that we don't need to have a separate
465-
* index.html's content watcher, auto-reloading will work automatically,
466-
* like other files managed by webpack in `frontend/` folder.
474+
* served by webpack or vite in dev-mode and read from classpath in
475+
* production mode.
476+
* <p>
477+
* NOTE: In dev mode, the file content is fetched using an http request so
478+
* that we don't need to have a separate index.html's content watcher.
479+
* Auto-reloading will work automatically, like other files managed by
480+
* webpack in `frontend/` folder.
467481
*
468482
* @param service
469483
* the vaadin service
@@ -478,6 +492,29 @@ public static String getIndexHtmlContent(VaadinService service)
478492
return getFileContent(service, INDEX_HTML);
479493
}
480494

495+
/**
496+
* Gets the content of the <code>frontend/web-component.html</code> file
497+
* which is served by webpack or vite in dev-mode and read from classpath in
498+
* production mode.
499+
* <p>
500+
* NOTE: In dev mode, the file content is fetched using an http request so
501+
* that we don't need to have a separate web-component.html's content
502+
* watcher. Auto-reloading will work automatically, like other files managed
503+
* by webpack in `frontend/` folder.
504+
*
505+
* @param service
506+
* the vaadin service
507+
* @return the content of the web-component.html file as a string, null if
508+
* not found.
509+
* @throws IOException
510+
* on error when reading file
511+
*
512+
*/
513+
public static String getWebComponentHtmlContent(VaadinService service)
514+
throws IOException {
515+
return getFileContent(service, WEB_COMPONENT_HTML);
516+
}
517+
481518
private static String getFileContent(VaadinService service, String path)
482519
throws IOException {
483520
DeploymentConfiguration config = service.getDeploymentConfiguration();

‎flow-server/src/main/java/com/vaadin/flow/server/frontend/NodeTasks.java‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,8 @@ public Builder withPostinstallPackages(
696696
TaskGenerateOpenAPI.class,
697697
TaskGenerateEndpoint.class,
698698
TaskGenerateBootstrap.class,
699+
TaskGenerateWebComponentHtml.class,
700+
TaskGenerateWebComponentBootstrap.class,
699701
TaskGenerateFeatureFlags.class,
700702
TaskInstallWebpackPlugins.class,
701703
TaskUpdatePackages.class,
@@ -731,8 +733,17 @@ private NodeTasks(Builder builder) {
731733
if (builder.generateEmbeddableWebComponents) {
732734
FrontendWebComponentGenerator generator = new FrontendWebComponentGenerator(
733735
classFinder);
734-
generator.generateWebComponents(builder.generatedFolder,
736+
Set<File> webComponents = generator.generateWebComponents(
737+
builder.generatedFolder,
735738
frontendDependencies.getThemeDefinition());
739+
740+
if (webComponents.size() > 0) {
741+
commands.add(new TaskGenerateWebComponentHtml(
742+
builder.frontendDirectory));
743+
commands.add(new TaskGenerateWebComponentBootstrap(
744+
builder.frontendDirectory,
745+
new File(builder.generatedFolder, IMPORTS_NAME)));
746+
}
736747
}
737748

738749
TaskUpdatePackages packageUpdater = null;
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
* Copyright 2000-2022 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.flow.server.frontend;
17+
18+
import java.io.File;
19+
import java.util.ArrayList;
20+
import java.util.List;
21+
22+
import static com.vaadin.flow.server.frontend.FrontendUtils.WEB_COMPONENT_BOOTSTRAP_FILE_NAME;
23+
import static com.vaadin.flow.server.frontend.FrontendUtils.GENERATED;
24+
25+
/**
26+
* A task for generating the bootstrap file for exported web components
27+
* {@link FrontendUtils#WEB_COMPONENT_BOOTSTRAP_FILE_NAME} during `package`
28+
* Maven goal.
29+
* <p>
30+
* For internal use only. May be renamed or removed in a future release.
31+
*
32+
* @author Vaadin Ltd
33+
*/
34+
public class TaskGenerateWebComponentBootstrap
35+
extends AbstractTaskClientGenerator {
36+
37+
private final File frontendGeneratedDirectory;
38+
private final File generatedImports;
39+
40+
/**
41+
* Create a task to generate <code>vaadin-web-component.ts</code> if
42+
* necessary.
43+
*
44+
* @param frontendDirectory
45+
* frontend directory is to check if the file already exists
46+
* there.
47+
* @param generatedImports
48+
* the flow generated imports file to include in the
49+
* <code>vaadin-web-component.ts</code>
50+
*/
51+
TaskGenerateWebComponentBootstrap(File frontendDirectory,
52+
File generatedImports) {
53+
this.frontendGeneratedDirectory = new File(frontendDirectory,
54+
GENERATED);
55+
this.generatedImports = generatedImports;
56+
}
57+
58+
@Override
59+
protected String getFileContent() {
60+
List<String> lines = new ArrayList<>();
61+
62+
String generatedImportsRelativePath = FrontendUtils
63+
.getUnixRelativePath(frontendGeneratedDirectory.toPath(),
64+
generatedImports.toPath())
65+
.replaceFirst("\\.(js|ts)$", "");
66+
67+
lines.add(String.format("import '%s';", generatedImportsRelativePath));
68+
lines.add("import { init } from '@vaadin/flow-frontend/FlowClient';");
69+
lines.add("init();");
70+
71+
return String.join(System.lineSeparator(), lines);
72+
}
73+
74+
@Override
75+
protected File getGeneratedFile() {
76+
return new File(frontendGeneratedDirectory,
77+
WEB_COMPONENT_BOOTSTRAP_FILE_NAME);
78+
}
79+
80+
@Override
81+
protected boolean shouldGenerate() {
82+
return true;
83+
}
84+
}

0 commit comments

Comments
 (0)