Skip to content

Commit ba1db11

Browse files
authored
feat: enable pwa for vite (#12363) (#12507)
Enable pwa installation for vite. PWA doesn't work in development mode with this feature. Part of #12052
1 parent d3d362e commit ba1db11

10 files changed

Lines changed: 135 additions & 24 deletions

File tree

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

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -788,10 +788,17 @@ private NodeTasks(Builder builder) {
788788

789789
if (featureFlags.isEnabled(FeatureFlags.VITE)) {
790790
String themeName = "";
791+
PwaConfiguration pwa;
791792
if (frontendDependencies != null) {
792-
themeName = frontendDependencies.getThemeDefinition().getName();
793+
if (frontendDependencies.getThemeDefinition() != null) {
794+
themeName = frontendDependencies.getThemeDefinition()
795+
.getName();
796+
}
797+
pwa = frontendDependencies.getPwaConfiguration();
798+
} else {
799+
pwa = new PwaConfiguration();
793800
}
794-
commands.add(new TaskUpdateSettingsFile(builder, themeName));
801+
commands.add(new TaskUpdateSettingsFile(builder, themeName, pwa));
795802
commands.add(new TaskUpdateVite(builder.npmFolder,
796803
builder.buildDirectory));
797804
} else if (enableWebpackConfigUpdate) {

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,7 @@ Map<String, String> getDefaultDevDependencies() {
392392
defaults.put("rollup-plugin-brotli", "3.1.0");
393393
defaults.put("vite-plugin-checker", "0.3.4");
394394
defaults.put("mkdirp", "1.0.4"); // for application-theme-plugin
395+
defaults.put("workbox-build", "6.4.1");
395396
} else {
396397
// Webpack plugins and helpers
397398
defaults.put("esbuild-loader", "2.15.1");

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

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,20 @@
2020
import java.io.IOException;
2121
import java.io.Serializable;
2222
import java.nio.charset.StandardCharsets;
23+
import java.nio.file.Path;
24+
import java.nio.file.Paths;
2325

2426
import org.apache.commons.io.FileUtils;
2527
import org.slf4j.Logger;
2628
import org.slf4j.LoggerFactory;
2729

30+
import com.vaadin.flow.server.PwaConfiguration;
31+
2832
import elemental.json.Json;
2933
import elemental.json.JsonObject;
3034
import static com.vaadin.flow.server.Constants.VAADIN_WEBAPP_RESOURCES;
35+
import static com.vaadin.flow.server.frontend.FrontendUtils.SERVICE_WORKER_SRC;
36+
import static com.vaadin.flow.server.frontend.FrontendUtils.SERVICE_WORKER_SRC_JS;
3137
import static com.vaadin.flow.shared.ApplicationConstants.VAADIN_STATIC_FILES_PATH;
3238
import static elemental.json.impl.JsonUtil.stringify;
3339

@@ -46,14 +52,17 @@ public class TaskUpdateSettingsFile implements FallibleCommand, Serializable {
4652
File webappResourcesDirectory;
4753
String buildDirectory;
4854
String themeName;
55+
PwaConfiguration pwaConfiguration;
4956

50-
TaskUpdateSettingsFile(NodeTasks.Builder builder, String themeName) {
57+
TaskUpdateSettingsFile(NodeTasks.Builder builder, String themeName,
58+
PwaConfiguration pwaConfiguration) {
5159
this.npmFolder = builder.getNpmFolder();
5260
this.frontendDirectory = builder.getFrontendDirectory();
5361
this.generatedFolder = builder.getGeneratedFolder();
5462
this.webappResourcesDirectory = builder.getWebappResourcesDirectory();
5563
this.buildDirectory = builder.getBuildDirectory();
5664
this.themeName = themeName;
65+
this.pwaConfiguration = pwaConfiguration;
5766
}
5867

5968
@Override
@@ -86,6 +95,12 @@ public void execute() {
8695

8796
settings.put("themeName", themeName);
8897

98+
settings.put("clientServiceWorkerSource", getServiceWorkerFile());
99+
100+
settings.put("pwaEnabled", pwaConfiguration.isEnabled());
101+
102+
settings.put("offlinePath", getOfflinePath());
103+
89104
File settingsFile = new File(npmFolder,
90105
buildDirectory + "/" + DEV_SETTINGS_FILE);
91106

@@ -108,6 +123,42 @@ private String combinePath(String... parts) {
108123
return path.toString();
109124
}
110125

126+
private String getServiceWorkerFile() {
127+
boolean exists = new File(frontendDirectory, SERVICE_WORKER_SRC)
128+
.exists()
129+
|| new File(frontendDirectory, SERVICE_WORKER_SRC_JS).exists();
130+
131+
String serviceWorkerFile = SERVICE_WORKER_SRC;
132+
if (new File(frontendDirectory, SERVICE_WORKER_SRC_JS).exists()) {
133+
serviceWorkerFile = SERVICE_WORKER_SRC_JS;
134+
}
135+
136+
if (!exists) {
137+
Path path = Paths.get(npmFolder.toString(), buildDirectory,
138+
serviceWorkerFile);
139+
return path.toString();
140+
} else {
141+
return Paths.get(frontendDirectory.toString(), serviceWorkerFile)
142+
.toString();
143+
}
144+
}
145+
146+
private String getOfflinePath() {
147+
if (pwaConfiguration.isOfflinePathEnabled()) {
148+
return "'" + getEscapedRelativePath(
149+
Paths.get(pwaConfiguration.getOfflinePath())) + "'";
150+
}
151+
return "'.'";
152+
}
153+
154+
private String getEscapedRelativePath(Path path) {
155+
if (path.isAbsolute()) {
156+
return FrontendUtils.getUnixRelativePath(npmFolder.toPath(), path);
157+
} else {
158+
return FrontendUtils.getUnixPath(path);
159+
}
160+
}
161+
111162
private Logger log() {
112163
return LoggerFactory.getLogger(this.getClass());
113164
}

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -210,9 +210,6 @@ private List<Pair<String, String>> getReplacements() {
210210
getClientEntryPoint()),
211211
new Pair<>("const pwaEnabled",
212212
Boolean.toString(pwaConfiguration.isEnabled())),
213-
new Pair<>("const offlinePathEnabled",
214-
Boolean.toString(
215-
pwaConfiguration.isOfflinePathEnabled())),
216213
new Pair<>("const offlinePath", getOfflinePath()),
217214
new Pair<>("const clientServiceWorkerEntryPoint",
218215
getClientServiceWorker()),
@@ -255,8 +252,11 @@ private String getEscapedRelativeWebpackPath(Path path) {
255252
}
256253

257254
private String getOfflinePath() {
258-
return "'" + getEscapedRelativeWebpackPath(
259-
Paths.get(pwaConfiguration.getOfflinePath())) + "'";
255+
if (pwaConfiguration.isOfflinePathEnabled()) {
256+
return "'" + getEscapedRelativeWebpackPath(
257+
Paths.get(pwaConfiguration.getOfflinePath())) + "'";
258+
}
259+
return "'.'";
260260
}
261261

262262
private String formatPathResolve(String path) {

‎flow-server/src/main/resources/com/vaadin/flow/server/frontend/sw.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ declare var self: ServiceWorkerGlobalScope & {
1515
skipWaiting();
1616
clientsClaim();
1717

18-
declare var OFFLINE_PATH_ENABLED: boolean; // defined by webpack.generated.js
1918
declare var OFFLINE_PATH: string; // defined by webpack.generated.js
2019

2120
/**
@@ -30,8 +29,7 @@ const rewriteBaseHref = async (response: Response) => {
3029
return new Response(html.replace(/<base\s+href=[^>]*>/, `<base href="${self.registration.scope}">`), response);
3130
};
3231

33-
const appShellPath = '.';
34-
const offlinePath = OFFLINE_PATH_ENABLED ? OFFLINE_PATH : appShellPath;
32+
const offlinePath = OFFLINE_PATH;
3533
const networkOnly = new NetworkOnly();
3634
let connectionLost = false;
3735

‎flow-server/src/main/resources/vite.generated.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ import * as net from 'net';
1010
import { processThemeResources } from '@vaadin/application-theme-plugin/theme-handle.js';
1111
import settings from '#settingsImport#';
1212
import { UserConfigFn, defineConfig, HtmlTagDescriptor, mergeConfig } from 'vite';
13+
import { injectManifest } from 'workbox-build';
1314

1415
import brotli from 'rollup-plugin-brotli';
1516
import checker from 'vite-plugin-checker';
1617

18+
1719
const frontendFolder = path.resolve(__dirname, settings.frontendFolder);
1820
const themeFolder = path.resolve(frontendFolder, settings.themeFolder);
1921
const frontendBundleFolder = path.resolve(__dirname, settings.frontendBundleOutput);
@@ -83,6 +85,7 @@ const allowedFrontendFolders = [
8385
export const vaadinConfig: UserConfigFn = (env) => {
8486
const devMode = env.mode === 'development';
8587
const basePath = env.mode === 'production' ? '' : '/VAADIN/';
88+
let pwaConfig;
8689

8790
if (devMode && process.env.watchDogPort) {
8891
// Open a connection with the Java dev-mode handler in order to finish
@@ -98,6 +101,10 @@ export const vaadinConfig: UserConfigFn = (env) => {
98101
Frontend: frontendFolder
99102
}
100103
},
104+
define: {
105+
// should be settings.offlinePath after manifests are fixed
106+
OFFLINE_PATH: "'.'"
107+
},
101108
server: {
102109
fs: {
103110
allow: allowedFrontendFolders,
@@ -114,6 +121,57 @@ export const vaadinConfig: UserConfigFn = (env) => {
114121
},
115122
plugins: [
116123
!devMode && brotli(),
124+
settings.pwaEnabled &&
125+
{
126+
name: 'pwa',
127+
enforce: 'post',
128+
apply: 'build',
129+
async configResolved(config) {
130+
pwaConfig = config;
131+
},
132+
async buildStart() {
133+
// Before inject manifest we need to resolve and transpile the sw.ts file
134+
// This could probably be made another way which needs to be investigated
135+
136+
// eslint-disable-next-line @typescript-eslint/no-var-requires
137+
const rollup = require('rollup') as typeof Rollup
138+
const includedPluginNames = [
139+
'alias',
140+
'vite:resolve',
141+
'vite:esbuild',
142+
'replace',
143+
'vite:define',
144+
'rollup-plugin-dynamic-import-variables',
145+
'vite:esbuild-transpile',
146+
'vite:terser',
147+
]
148+
const plugins = pwaConfig.plugins.filter(p => includedPluginNames.includes(p.name)) as Plugin[]
149+
const bundle = await rollup.rollup({
150+
input: path.resolve(settings.clientServiceWorkerSource),
151+
plugins,
152+
})
153+
try {
154+
await bundle.write({
155+
format: 'es',
156+
exports: 'none',
157+
inlineDynamicImports: true,
158+
file: path.resolve(frontendBundleFolder, 'sw.js'),
159+
160+
})
161+
}
162+
finally {
163+
await bundle.close()
164+
}
165+
// end of resolve and transpilation
166+
167+
await injectManifest({
168+
swSrc: path.resolve(frontendBundleFolder, 'sw.js'),
169+
swDest: path.resolve(frontendBundleFolder, 'sw.js'),
170+
globDirectory: frontendBundleFolder,
171+
injectionPoint: 'self.__WB_MANIFEST',
172+
});
173+
}
174+
},
117175
{
118176
name: 'custom-theme',
119177
config() {

‎flow-server/src/main/resources/webpack.generated.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ const useClientSideIndexFileForBootstrapping = '[to-be-generated-by-flow]';
3939
const clientSideIndexHTML = '[to-be-generated-by-flow]';
4040
const clientSideIndexEntryPoint = '[to-be-generated-by-flow]';
4141
const pwaEnabled = false; // to be generated by flow;
42-
const offlinePathEnabled = false; // to be generated by flow;
4342
const offlinePath = '[to-be-generated-by-flow]';
4443
const clientServiceWorkerEntryPoint = '[to-be-generated-by-flow]';
4544
// public path for resources, must match Flow VAADIN_BUILD
@@ -165,7 +164,6 @@ const createServiceWorkerPlugin = function () {
165164
],
166165
webpackCompilationPlugins: [
167166
new DefinePlugin({
168-
OFFLINE_PATH_ENABLED: offlinePathEnabled,
169167
OFFLINE_PATH: JSON.stringify(offlinePath)
170168
})
171169
]

‎flow-server/src/test/java/com/vaadin/flow/server/frontend/TaskGenerateServicWorkerTest.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
import org.junit.Rule;
2727
import org.junit.Test;
2828
import org.junit.rules.TemporaryFolder;
29+
import org.mockito.Mockito;
30+
31+
import com.vaadin.experimental.FeatureFlags;
32+
import com.vaadin.flow.di.Lookup;
2933

3034
import static com.vaadin.flow.server.frontend.FrontendUtils.SERVICE_WORKER_SRC;
3135
import static com.vaadin.flow.server.frontend.FrontendUtils.SERVICE_WORKER_SRC_JS;;

‎flow-server/src/test/java/com/vaadin/flow/server/frontend/TaskUpdateViteTest.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import org.mockito.Mockito;
1616

1717
import com.vaadin.flow.di.Lookup;
18+
import com.vaadin.flow.server.PwaConfiguration;
1819

1920
import elemental.json.Json;
2021
import elemental.json.JsonObject;
@@ -93,7 +94,7 @@ public void usedSettings_matchThoseCreatedToSettingsFile()
9394
temporaryFolder.newFolder("frontend"), "target");
9495

9596
TaskUpdateSettingsFile updateSettings = new TaskUpdateSettingsFile(
96-
builder, "theme");
97+
builder, "theme", new PwaConfiguration());
9798
updateSettings.execute();
9899
File settings = new File(temporaryFolder.getRoot(),
99100
"target/" + DEV_SETTINGS_FILE);

‎flow-server/src/test/java/com/vaadin/flow/server/frontend/TaskUpdateWebpackTest.java‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -215,16 +215,12 @@ public void should_setClientSideBootstrapMode_when_runningV15Bootstrapping()
215215
}
216216

217217
@Test
218-
public void should_disableOfflinePath_when_defaultInPwa()
219-
throws IOException {
218+
public void should_useAppShellPath_when_defaultInPwa() throws IOException {
220219
webpackUpdater.execute();
221220
String webpackGeneratedContents = Files.lines(webpackGenerated.toPath())
222221
.collect(Collectors.joining("\n"));
223-
Assert.assertTrue("offlinePathEnabled should be false by default",
224-
webpackGeneratedContents
225-
.contains("const offlinePathEnabled = false;"));
226-
Assert.assertTrue("offlinePath should be empty by default",
227-
webpackGeneratedContents.contains("const offlinePath = '';"));
222+
Assert.assertTrue("offlinePath should be appShellPath '.' by default",
223+
webpackGeneratedContents.contains("const offlinePath = '.';"));
228224
}
229225

230226
@Test
@@ -238,9 +234,6 @@ public void should_enableCustomOfflinePath_when_customisedInPwa()
238234
String webpackGeneratedContents = Files.lines(webpackGenerated.toPath())
239235
.collect(Collectors.joining("\n"));
240236

241-
Assert.assertTrue("offlinePathEnabled should be true",
242-
webpackGeneratedContents
243-
.contains("const offlinePathEnabled = true;"));
244237
Assert.assertTrue("offlinePath should be customizable",
245238
webpackGeneratedContents
246239
.contains("const offlinePath = 'off.html';"));

0 commit comments

Comments
 (0)