Skip to content

Commit f827649

Browse files
authored
fix: make Vite work with custom frontend directory (#14152) (CP: 23.1) (#14222)
Fixes Vite configuration to work with a custom frontend directory. Also rewrite theme css to resolve urls for assets defined in theme.json Fixes #14046 Fixes #14102
1 parent 47c7287 commit f827649

11 files changed

Lines changed: 593 additions & 80 deletions

File tree

‎flow-server/src/main/resources/plugins/application-theme-plugin/theme-generator.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ function generateThemeFile(themeFolder, themeName, themeProperties, productionMo
174174
}
175175
themeProperties.documentCss.forEach((cssImport) => {
176176
const variable = 'module' + i++;
177-
imports.push(`import ${variable} from '${cssImport}';\n`);
177+
imports.push(`import ${variable} from '${cssImport}?inline';\n`);
178178
// Due to chrome bug https://bugs.chromium.org/p/chromium/issues/detail?id=336876 font-face will not work
179179
// inside shadowRoot so we need to inject it there also.
180180
globalCssCode.push(`if(target !== document) {

‎flow-server/src/main/resources/plugins/theme-loader/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"url": "https://github.com/vaadin/flow/issues"
1515
},
1616
"files": [
17-
"theme-loader.js"
17+
"theme-loader.js",
18+
"theme-loader-utils.js"
1819
]
1920
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
const fs = require('fs');
2+
const path = require('path');
3+
const glob = require('glob');
4+
5+
// Collect groups [url(] ['|"]optional './|../', file part and end of url
6+
const urlMatcher = /(url\(\s*)(\'|\")?(\.\/|\.\.\/)(\S*)(\2\s*\))/g;
7+
8+
9+
function assetsContains(fileUrl, themeFolder, logger) {
10+
const themeProperties = getThemeProperties(themeFolder);
11+
if (!themeProperties) {
12+
logger.debug('No theme properties found.');
13+
return false;
14+
}
15+
const assets = themeProperties['assets'];
16+
if (!assets) {
17+
logger.debug('No defined assets in theme properties');
18+
return false;
19+
}
20+
// Go through each asset module
21+
for (let module of Object.keys(assets)) {
22+
const copyRules = assets[module];
23+
logger.log('asset ' + module);
24+
// Go through each copy rule
25+
for (let copyRule of Object.keys(copyRules)) {
26+
logger.log('rule ' + copyRules[copyRule] + " ---> file " + fileUrl);
27+
// if file starts with copyRule target check if file with path after copy target can be found
28+
if (fileUrl.startsWith(copyRules[copyRule])) {
29+
const targetFile = fileUrl.replace(copyRules[copyRule], '');
30+
const files = glob.sync(path.resolve('node_modules/', module, copyRule), { nodir: true });
31+
32+
logger.log('targetFile ' + targetFile);
33+
for (let file of files) {
34+
if (file.endsWith(targetFile)) return true;
35+
}
36+
}
37+
}
38+
}
39+
return false;
40+
}
41+
42+
function getThemeProperties(themeFolder) {
43+
const themePropertyFile = path.resolve(themeFolder, 'theme.json');
44+
if (!fs.existsSync(themePropertyFile)) {
45+
return {};
46+
}
47+
const themePropertyFileAsString = fs.readFileSync(themePropertyFile);
48+
if (themePropertyFileAsString.length === 0) {
49+
return {};
50+
}
51+
return JSON.parse(themePropertyFileAsString);
52+
}
53+
54+
55+
function rewriteCssUrls(source, handledResourceFolder, themeFolder, logger, options) {
56+
source = source.replace(urlMatcher, function (match, url, quoteMark, replace, fileUrl, endString) {
57+
let absolutePath = path.resolve(handledResourceFolder, replace, fileUrl);
58+
const existingThemeResource = absolutePath.startsWith(themeFolder) && fs.existsSync(absolutePath);
59+
if (
60+
existingThemeResource || assetsContains(fileUrl, themeFolder, logger)
61+
) {
62+
// Adding ./ will skip css-loader, which should be done for asset files
63+
const skipLoader = existingThemeResource ? '' : './';
64+
const frontendThemeFolder = skipLoader + 'themes/' + path.basename(themeFolder);
65+
logger.debug(
66+
'Updating url for file',
67+
"'" + replace + fileUrl + "'",
68+
'to use',
69+
"'" + frontendThemeFolder + '/' + fileUrl + "'"
70+
);
71+
const pathResolved = absolutePath.substring(themeFolder.length).replace(/\\/g, '/');
72+
73+
// keep the url the same except replace the ./ or ../ to themes/[themeFolder]
74+
return url + (quoteMark??'') + frontendThemeFolder + pathResolved + endString;
75+
} else if (options.devMode) {
76+
logger.log("No rewrite for '", match, "' as the file was not found.");
77+
}
78+
return match;
79+
});
80+
return source;
81+
}
82+
83+
module.exports = { rewriteCssUrls };
Lines changed: 2 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
const loaderUtils = require('loader-utils');
22
const fs = require('fs');
33
const path = require('path');
4-
5-
// Collect groups [url(] [ |'|"]optional './|../', file part and end of url
6-
const urlMatcher = /(url\()(\'|\")?(\.\/|\.\.\/)(\S*)(\2\))/g;
4+
const { rewriteCssUrls } = require('./theme-loader-utils');
75

86
/**
97
* This custom loader handles rewriting urls for the application theme css files.
@@ -31,75 +29,6 @@ module.exports = function (source, map) {
3129

3230
logger.log("Using '", themeFolder, "' for the application theme base folder.");
3331

34-
source = source.replace(urlMatcher, function (match, url, quoteMark, replace, fileUrl, endString) {
35-
let absolutePath = path.resolve(handledResourceFolder, replace, fileUrl);
36-
if (
37-
(fs.existsSync(absolutePath) && absolutePath.startsWith(themeFolder)) ||
38-
assetsContains(fileUrl, themeFolder, logger)
39-
) {
40-
// Adding ./ will skip css-loader, which should be done for asset files
41-
const skipLoader = fs.existsSync(absolutePath) && absolutePath.startsWith(themeFolder) ? '' : './';
42-
const frontendThemeFolder = skipLoader + 'themes/' + path.basename(themeFolder);
43-
logger.debug(
44-
'Updating url for file',
45-
"'" + replace + fileUrl + "'",
46-
'to use',
47-
"'" + frontendThemeFolder + '/' + fileUrl + "'"
48-
);
49-
const pathResolved = absolutePath.substring(themeFolder.length).replace(/\\/g, '/');
50-
51-
// keep the url the same except replace the ./ or ../ to themes/[themeFolder]
52-
if (quoteMark) {
53-
return url + quoteMark + frontendThemeFolder + pathResolved + endString;
54-
}
55-
return url + frontendThemeFolder + pathResolved + endString;
56-
} else if (options.devMode) {
57-
logger.log("No rewrite for '", match, "' as the file was not found.");
58-
}
59-
return match;
60-
});
61-
32+
source = rewriteCssUrls(source, handledResourceFolder, themeFolder, logger, options);
6233
this.callback(null, source, map);
6334
};
64-
65-
function assetsContains(fileUrl, themeFolder, logger) {
66-
const themeProperties = getThemeProperties(themeFolder);
67-
if (!themeProperties) {
68-
logger.debug('No theme properties found.');
69-
return false;
70-
}
71-
const assets = themeProperties['assets'];
72-
if (!assets) {
73-
logger.debug('No defined assets in theme properties');
74-
return false;
75-
}
76-
// Go through each asset module
77-
for (let module of Object.keys(assets)) {
78-
const copyRules = assets[module];
79-
// Go through each copy rule
80-
for (let copyRule of Object.keys(copyRules)) {
81-
// if file starts with copyRule target check if file with path after copy target can be found
82-
if (fileUrl.startsWith(copyRules[copyRule])) {
83-
const targetFile = fileUrl.replace(copyRules[copyRule], '');
84-
const files = require('glob').sync(path.resolve('node_modules/', module, copyRule), { nodir: true });
85-
86-
for (let file of files) {
87-
if (file.endsWith(targetFile)) return true;
88-
}
89-
}
90-
}
91-
}
92-
return false;
93-
}
94-
95-
function getThemeProperties(themeFolder) {
96-
const themePropertyFile = path.resolve(themeFolder, 'theme.json');
97-
if (!fs.existsSync(themePropertyFile)) {
98-
return {};
99-
}
100-
const themePropertyFileAsString = fs.readFileSync(themePropertyFile);
101-
if (themePropertyFileAsString.length === 0) {
102-
return {};
103-
}
104-
return JSON.parse(themePropertyFileAsString);
105-
}

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

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { readFileSync, existsSync, writeFileSync } from 'fs';
99
import * as net from 'net';
1010

1111
import { processThemeResources } from '#buildFolder#/plugins/application-theme-plugin/theme-handle';
12+
import { rewriteCssUrls } from '#buildFolder#/plugins/theme-loader/theme-loader-utils';
1213
import settings from '#settingsImport#';
1314
import { defineConfig, mergeConfig, PluginOption, ResolvedConfig, UserConfigFn, OutputOptions, AssetInfo, ChunkInfo } from 'vite';
1415
import { injectManifest } from 'workbox-build';
@@ -305,7 +306,7 @@ export { ${exports.map((binding) => `${binding} as ${binding}`).join(', ')} };`;
305306
};
306307
}
307308

308-
function themePlugin(): PluginOption {
309+
function themePlugin(opts): PluginOption {
309310
return {
310311
name: 'vaadin:theme',
311312
config() {
@@ -336,6 +337,15 @@ function themePlugin(): PluginOption {
336337
}
337338
}
338339
},
340+
async transform(raw, id, options) {
341+
// rewrite urls for the application theme css files
342+
const [bareId, query] = id.split('?');
343+
if (!bareId?.startsWith(themeFolder) || !bareId?.endsWith(".css")) {
344+
return;
345+
}
346+
const [themeName] = bareId.substring(themeFolder.length + 1).split('/');
347+
return rewriteCssUrls(raw, path.dirname(bareId), path.resolve(themeFolder, themeName), console, opts);
348+
}
339349
}
340350
}
341351

@@ -361,7 +371,7 @@ const allowedFrontendFolders = [
361371
frontendFolder,
362372
addonFrontendFolder,
363373
path.resolve(addonFrontendFolder, '..', 'frontend'), // Contains only generated-flow-imports
364-
path.resolve(frontendFolder, '../node_modules')
374+
path.resolve(__dirname, 'node_modules')
365375
];
366376

367377
export const vaadinConfig: UserConfigFn = (env) => {
@@ -374,7 +384,7 @@ export const vaadinConfig: UserConfigFn = (env) => {
374384
}
375385

376386
return {
377-
root: 'frontend',
387+
root: frontendFolder,
378388
base: '',
379389
resolve: {
380390
alias: {
@@ -422,7 +432,7 @@ export const vaadinConfig: UserConfigFn = (env) => {
422432
settings.offlineEnabled && buildSWPlugin(),
423433
settings.offlineEnabled && injectManifestToSWPlugin(),
424434
!devMode && statsExtracterPlugin(),
425-
themePlugin(),
435+
themePlugin({devMode}),
426436
{
427437
name: 'vaadin:force-remove-spa-middleware',
428438
transformIndexHtml: {

‎flow-tests/test-custom-frontend-directory/pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
<modules>
2525
<module>test-themes-custom-frontend-directory/pom.xml</module>
2626
<module>test-themes-custom-frontend-directory/pom-generatedTsDir.xml</module>
27+
<module>test-themes-custom-frontend-directory/pom-vite.xml</module>
2728
</modules>
2829
</profile>
2930
</profiles>
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<parent>
6+
<groupId>com.vaadin</groupId>
7+
<artifactId>test-custom-frontend-directory</artifactId>
8+
<version>23.1-SNAPSHOT</version>
9+
</parent>
10+
<artifactId>flow-test-themes-custom-frontend-directory-vite</artifactId>
11+
<name>Flow themes tests in Vite with custom frontend directory</name>
12+
<packaging>war</packaging>
13+
<properties>
14+
<maven.deploy.skip>true</maven.deploy.skip>
15+
<vaadin.devmode.liveReload.enabled>true</vaadin.devmode.liveReload.enabled>
16+
<vaadin.pnpm.enable>false</vaadin.pnpm.enable>
17+
</properties>
18+
19+
<dependencies>
20+
<dependency>
21+
<groupId>com.vaadin</groupId>
22+
<artifactId>flow-test-common</artifactId>
23+
<version>${project.version}</version>
24+
</dependency>
25+
<dependency>
26+
<groupId>com.vaadin</groupId>
27+
<artifactId>flow-html-components-testbench</artifactId>
28+
<version>${project.version}</version>
29+
<scope>test</scope>
30+
</dependency>
31+
<dependency>
32+
<groupId>com.vaadin</groupId>
33+
<artifactId>vaadin-dev-server</artifactId>
34+
<version>${project.version}</version>
35+
</dependency>
36+
<dependency>
37+
<groupId>com.vaadin</groupId>
38+
<artifactId>flow-test-lumo</artifactId>
39+
<version>${project.version}</version>
40+
</dependency>
41+
</dependencies>
42+
43+
<build>
44+
<resources>
45+
<resource>
46+
<directory>${project.basedir}/src/main/vite-resources</directory>
47+
</resource>
48+
</resources>
49+
<testSourceDirectory>${project.basedir}/src/test-vite/java</testSourceDirectory>
50+
<plugins>
51+
<plugin>
52+
<groupId>org.eclipse.jetty</groupId>
53+
<artifactId>jetty-maven-plugin</artifactId>
54+
</plugin>
55+
<plugin>
56+
<groupId>com.vaadin</groupId>
57+
<artifactId>flow-maven-plugin</artifactId>
58+
<configuration>
59+
<frontendDirectory>${project.basedir}/side-src/main/frontend</frontendDirectory>
60+
<productionMode>false</productionMode>
61+
</configuration>
62+
<executions>
63+
<execution>
64+
<id>ensure-fronted-deleted</id>
65+
<goals>
66+
<goal>clean-frontend</goal>
67+
</goals>
68+
<phase>initialize</phase>
69+
</execution>
70+
</executions>
71+
</plugin>
72+
<plugin>
73+
<groupId>org.apache.maven.plugins</groupId>
74+
<artifactId>maven-clean-plugin</artifactId>
75+
<executions>
76+
<execution>
77+
<id>ensure-fronted-deleted</id>
78+
<goals>
79+
<goal>clean</goal>
80+
</goals>
81+
<phase>initialize</phase>
82+
<configuration>
83+
<directory>${project.basedir}/frontend</directory>
84+
<failOnError>false</failOnError>
85+
</configuration>
86+
</execution>
87+
</executions>
88+
</plugin>
89+
</plugins>
90+
</build>
91+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
com.vaadin.experimental.viteForFrontendBuild=true

0 commit comments

Comments
 (0)