feat(web): replace cra with vite (#2457)

* feat(web): replace cra with vite

* fix: add istanbul
* fix: add jest
* fix: inject env vars
* fix: replicate cra output directories
* fix: post-frontend build for go templating
* fix: dynamic publicpath

* fix(web): import resolution with aliases for .module.css files

* refactor(server): baseurl var

* refactor(web): drop babel-jest for esbuild-jest

* refactor(web): add inline sourcemap for coverage bundle

* build(deps): update web deps

* build(deps): downgrade vite-plugin-istanbul to 2.2.0

98bf77dbaa is a breaking change that means production mode builds can no longer be instrumented.

* refactor(web): match frontend name and version

* refactor(web): drop cra readme
pull/2472/head
Amir Zarrinkafsh 2021-10-08 15:00:06 +11:00 committed by GitHub
parent 6e0536137c
commit a3e84769b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 1538 additions and 7571 deletions

View File

@ -3,7 +3,7 @@
set +u
if [[ "${BUILDKITE_LABEL}" == ":service_dog: Linting" ]]; then
cd web && pnpm install --shamefully-hoist && cd ../
cd web && pnpm install && cd ../
fi
if [[ "${BUILDKITE_LABEL}" == ":docker: Build Image [coverage]" ]]; then

View File

@ -10,7 +10,8 @@ COPY web ./
# Install the dependencies and build
RUN yarn global add pnpm && \
pnpm install --shamefully-hoist --frozen-lockfile && GENERATE_SOURCEMAP=false INLINE_RUNTIME_CHUNK=false pnpm coverage
pnpm install --frozen-lockfile && pnpm coverage && \
sed -i -e 's/{{.[a-zA-Z]*}}/"&"/g' /node/src/internal/server/public_html/index.html
# =======================================
# ===== Build image for the backend =====

View File

@ -8,7 +8,8 @@ WORKDIR /node/src/app
COPY web ./
# Install the dependencies and build
RUN yarn install --frozen-lockfile && GENERATE_SOURCEMAP=false INLINE_RUNTIME_CHUNK=false yarn build
RUN yarn install --frozen-lockfile && yarn build && \
sed -i -e 's/{{.[a-zA-Z]*}}/"&"/g' /node/src/internal/server/public_html/index.html
# =======================================
# ===== Build image for the backend =====

View File

@ -66,7 +66,7 @@ func buildAutheliaBinary(xflags []string, buildkite bool) {
}
func buildFrontend(branch string) {
cmd := utils.CommandWithStdout("pnpm", "install", "--shamefully-hoist")
cmd := utils.CommandWithStdout("pnpm", "install")
cmd.Dir = webDirectory
err := cmd.Run()
@ -78,7 +78,12 @@ func buildFrontend(branch string) {
cmd = utils.CommandWithStdout("pnpm", "build")
cmd.Dir = webDirectory
cmd.Env = append(os.Environ(), "GENERATE_SOURCEMAP=false", "INLINE_RUNTIME_CHUNK=false")
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
cmd = utils.CommandWithStdout("bash", "-c", "sed -i -e 's/{{.[a-zA-Z]*}}/\"&\"/g' internal/server/public_html/index.html")
err = cmd.Run()
if err != nil {

View File

@ -42,6 +42,7 @@ func ServeTemplatedFile(publicDir, file, rememberMe, resetPassword, session, the
base = baseURL.(string)
}
baseURL := "https://" + string(ctx.Request.Host()) + base + "/"
nonce := utils.RandomString(32, alphaNumericRunes)
switch extension := filepath.Ext(file); extension {
@ -60,7 +61,7 @@ func ServeTemplatedFile(publicDir, file, rememberMe, resetPassword, session, the
ctx.Response.Header.Add("Content-Security-Policy", fmt.Sprintf("default-src 'self' ; object-src 'none'; style-src 'self' 'nonce-%s'", nonce))
}
err := tmpl.Execute(ctx.Response.BodyWriter(), struct{ Base, CSPNonce, RememberMe, ResetPassword, Session, Theme string }{Base: base, CSPNonce: nonce, RememberMe: rememberMe, ResetPassword: resetPassword, Session: session, Theme: theme})
err := tmpl.Execute(ctx.Response.BodyWriter(), struct{ Base, BaseURL, CSPNonce, RememberMe, ResetPassword, Session, Theme string }{Base: base, BaseURL: baseURL, CSPNonce: nonce, RememberMe: rememberMe, ResetPassword: resetPassword, Session: session, Theme: theme})
if err != nil {
ctx.Error("an error occurred", 503)
logger.Errorf("Unable to execute template: %v", err)

View File

@ -55,7 +55,7 @@ func waitUntilAutheliaFrontendIsReady(dockerEnvironment *DockerEnvironment) erro
90*time.Second,
dockerEnvironment,
"authelia-frontend",
[]string{"You can now view web in the browser.", "Compiled with warnings", "Compiled successfully!"})
[]string{"vite v2.6.3 dev server running at", "ready in"})
}
func waitUntilSambaIsReady(dockerEnvironment *DockerEnvironment) error {

View File

@ -23,7 +23,7 @@ services:
- 'traefik.http.routers.authelia_frontend.entrypoints=https'
- 'traefik.http.routers.authelia_frontend.tls=true'
environment:
- PUBLIC_URL=${PathPrefix}
- VITE_PUBLIC_URL=${PathPrefix}
networks:
- authelianet
...

View File

@ -6,8 +6,8 @@ set -x
cd /
echo "Use hot reloaded version of Authelia backend"
go get github.com/cespare/reflex
go get github.com/go-delve/delve/cmd/dlv
go install github.com/cespare/reflex@latest
go install github.com/go-delve/delve/cmd/dlv@latest
cd /app

View File

@ -2,4 +2,4 @@
set -x
pnpm install --shamefully-hoist --frozen-lockfile && pnpm start
pnpm install --frozen-lockfile && pnpm start

View File

@ -69,7 +69,7 @@ http {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host "127.0.0.1";
proxy_set_header Host $host:$server_port;
proxy_pass $frontend_endpoint;
}

View File

@ -1,42 +0,0 @@
const isCoverage = process.env.COVERAGE === "true";
const babelPlugins = isCoverage ? ["babel-plugin-istanbul"] : [];
const cracoPlugins = isCoverage
? [
{
plugin: require("craco-alias"),
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.aliases.json",
},
},
]
: [
{
plugin: require("craco-alias"),
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.aliases.json",
},
},
{
plugin: require("craco-esbuild"),
options: {
enableSvgr: true,
esbuildMinimizerOptions: {
target: "es2015",
css: true,
minify: true,
},
skipEsbuildJest: true,
},
},
];
module.exports = {
babel: {
plugins: babelPlugins,
},
plugins: cracoPlugins,
};

View File

@ -1,5 +1,5 @@
HOST=authelia-frontend
PUBLIC_URL=""
REACT_APP_REMEMBER_ME=true
REACT_APP_RESET_PASSWORD=true
REACT_APP_THEME=light
VITE_HMR_PORT=8080
VITE_PUBLIC_URL=""
VITE_REMEMBER_ME=true
VITE_RESET_PASSWORD=true
VITE_THEME=light

View File

@ -1,5 +1,4 @@
BUILD_PATH=../internal/server/public_html
PUBLIC_URL={{.Base}}
REACT_APP_REMEMBER_ME={{.RememberMe}}
REACT_APP_RESET_PASSWORD={{.ResetPassword}}
REACT_APP_THEME={{.Theme}}
VITE_PUBLIC_URL={{.Base}}
VITE_REMEMBER_ME={{.RememberMe}}
VITE_RESET_PASSWORD={{.ResetPassword}}
VITE_THEME={{.Theme}}

View File

@ -1,44 +0,0 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

22
web/index.html 100644
View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<base href="{{.BaseURL}}">
<meta property="csp-nonce" content="{{.CSPNonce}}" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Authelia login portal for your apps" />
<link rel="manifest" href="/manifest.json" />
<link rel="icon" href="/favicon.ico" />
<title>Login - Authelia</title>
</head>
<body data-basepath="<%- VITE_PUBLIC_URL %>" data-rememberme="<%- VITE_REMEMBER_ME %>" data-resetpassword="<%- VITE_RESET_PASSWORD %>" data-theme="<%- VITE_THEME %>">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>

View File

@ -1,6 +1,6 @@
{
"name": "web",
"version": "0.1.0",
"name": "authelia",
"version": "4.31.0",
"private": true,
"dependencies": {
"@fortawesome/fontawesome-svg-core": "1.2.36",
@ -9,6 +9,7 @@
"@fortawesome/react-fontawesome": "0.1.15",
"@material-ui/core": "4.12.3",
"@material-ui/icons": "4.11.2",
"@material-ui/styles": "4.11.4",
"axios": "0.22.0",
"classnames": "2.3.1",
"qrcode.react": "1.0.1",
@ -18,21 +19,90 @@
"react-ga": "3.3.0",
"react-loading": "2.0.3",
"react-otp-input": "2.4.0",
"react-router": "5.2.1",
"react-router-dom": "5.3.0",
"u2f-api": "1.2.1"
},
"scripts": {
"prepare": "cd .. && husky install .github",
"start": "craco start",
"build": "craco build",
"start": "vite --host",
"build": "vite build",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"coverage": "COVERAGE=true craco build",
"test": "craco test --coverage --no-cache",
"coverage": "VITE_COVERAGE=true vite build",
"test": "jest --coverage --no-cache",
"report": "nyc report -r clover -r json -r lcov -r text"
},
"eslintConfig": {
"extends": "react-app"
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.js"
],
"testMatch": [
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jsdom",
"transform": {
"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": [
"esbuild-jest",
{
"sourcemap": true
}
],
"^.+\\.(css|svg)$": "jest-transform-stub"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$"
],
"moduleNameMapper": {
"^@root/(.*)$": [
"<rootDir>/src/$1"
],
"^@assets/(.*)$": [
"<rootDir>/src/assets/$1"
],
"^@components/(.*)$": [
"<rootDir>/src/components/$1"
],
"^@constants/(.*)$": [
"<rootDir>/src/constants/$1"
],
"^@hooks/(.*)$": [
"<rootDir>/src/hooks/$1"
],
"^@layouts/(.*)$": [
"<rootDir>/src/layouts/$1"
],
"^@models/(.*)$": [
"<rootDir>/src/models/$1"
],
"^@services/(.*)$": [
"<rootDir>/src/services/$1"
],
"^@themes/(.*)$": [
"<rootDir>/src/themes/$1"
],
"^@utils/(.*)$": [
"<rootDir>/src/utils/$1"
],
"^@views/(.*)$": [
"<rootDir>/src/views/$1"
]
},
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
],
"resetMocks": true
},
"browserslist": {
"production": [
">0.2%",
@ -51,28 +121,37 @@
"devDependencies": {
"@commitlint/cli": "13.2.0",
"@commitlint/config-conventional": "13.2.0",
"@craco/craco": "6.3.0",
"@testing-library/jest-dom": "5.14.1",
"@testing-library/react": "12.1.2",
"@types/classnames": "2.3.0",
"@types/node": "15.6.0",
"@types/node": "16.10.3",
"@types/qrcode.react": "1.0.2",
"@types/query-string": "6.3.0",
"@types/react": "17.0.27",
"@types/react-dom": "17.0.9",
"@types/react-ga": "2.3.0",
"@types/react-router-dom": "5.3.1",
"babel-preset-react-app": "10.0.0",
"craco-alias": "3.0.1",
"craco-esbuild": "0.4.1",
"@typescript-eslint/eslint-plugin": "4.33.0",
"@typescript-eslint/parser": "4.33.0",
"esbuild-jest": "0.5.0",
"eslint-config-prettier": "8.3.0",
"eslint-config-react-app": "6.0.0",
"eslint-formatter-rdjson": "1.0.5",
"eslint-import-resolver-typescript": "2.5.0",
"eslint-plugin-flowtype": "6.1.0",
"eslint-plugin-import": "2.24.2",
"eslint-plugin-jsx-a11y": "6.4.1",
"eslint-plugin-prettier": "4.0.0",
"eslint-plugin-react": "7.26.1",
"eslint-plugin-react-hooks": "4.2.0",
"husky": "7.0.2",
"jest": "27.2.4",
"jest-transform-stub": "2.0.0",
"jest-watch-typeahead": "1.0.0",
"prettier": "2.4.1",
"react-scripts": "4.0.3",
"react-test-renderer": "17.0.2",
"typescript": "4.4.3"
"typescript": "4.4.3",
"vite": "2.6.4",
"vite-plugin-istanbul": "2.2.0",
"vite-plugin-svgr": "0.4.0",
"vite-react": "0.0.40",
"vite-tsconfig-paths": "3.3.14"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta property="csp-nonce" content="{{.CSPNonce}}" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Authelia login portal for your apps" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Login - Authelia</title>
</head>
<body data-basepath="%PUBLIC_URL%" data-rememberme="%REACT_APP_REMEMBER_ME%" data-resetpassword="%REACT_APP_RESET_PASSWORD%" data-theme="%REACT_APP_THEME%">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -2,7 +2,6 @@ import React from "react";
import ReactDOM from "react-dom";
import "@utils/AssetPath";
import "@root/index.css";
import App from "@root/App";
import * as serviceWorker from "@root/serviceWorker";

View File

@ -15,7 +15,7 @@ export interface Props {
const LoginLayout = function (props: Props) {
const style = useStyles();
return (
<Grid id={props.id} className={style.root} container spacing={0} alignItems="center" justify="center">
<Grid id={props.id} className={style.root} container spacing={0} alignItems="center" justifyContent="center">
<Container maxWidth="xs" className={style.rootContainer}>
<Grid container>
<Grid item xs={12}>

View File

@ -1,2 +1 @@
/// <reference types="react-scripts" />
declare var __webpack_public_path__: string;

View File

@ -1,7 +0,0 @@
import { getBasePath } from "@utils/BasePath";
__webpack_public_path__ = "/";
if (getBasePath() !== "") {
__webpack_public_path__ = getBasePath() + "/";
}

View File

@ -36,7 +36,7 @@ const MethodSelectionDialog = function (props: Props) {
return (
<Dialog open={props.open} className={style.root} onClose={props.onClose}>
<DialogContent>
<Grid container justify="center" spacing={1} id="methods-dialog">
<Grid container justifyContent="center" spacing={1} id="methods-dialog">
{props.methods.has(SecondFactorMethod.TOTP) ? (
<MethodItem
id="one-time-password-option"
@ -74,7 +74,7 @@ const MethodSelectionDialog = function (props: Props) {
export default MethodSelectionDialog;
const useStyles = makeStyles((theme) => ({
const useStyles = makeStyles(() => ({
root: {
textAlign: "center",
},

View File

@ -1,19 +0,0 @@
{
"compilerOptions": {
"baseUrl": "./src",
"jsx": "preserve",
"paths": {
"@root/*": ["./*"],
"@assets/*": ["assets/*"],
"@components/*": ["components/*"],
"@constants/*": ["constants/*"],
"@hooks/*": ["hooks/*"],
"@layouts/*": ["layouts/*"],
"@models/*": ["models/*"],
"@services/*": ["services/*"],
"@themes/*": ["themes/*"],
"@utils/*": ["utils/*"],
"@views/*": ["views/*"]
}
}
}

View File

@ -1,28 +1,43 @@
{
"extends": "./tsconfig.aliases.json",
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@root/*": ["./*"],
"@assets/*": ["assets/*"],
"@components/*": ["components/*"],
"@constants/*": ["constants/*"],
"@hooks/*": ["hooks/*"],
"@layouts/*": ["layouts/*"],
"@models/*": ["models/*"],
"@services/*": ["services/*"],
"@themes/*": ["themes/*"],
"@utils/*": ["utils/*"],
"@views/*": ["views/*"]
},
"target": "es6",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"types": ["@types/node", "vite/client", "vite-plugin-svgr/client"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noFallthroughCasesInSwitch": true
"jsx": "react-jsx"
},
"include": [
".*.js",
"vite.config.ts",
"src",
"types"
],

69
web/vite.config.ts 100644
View File

@ -0,0 +1,69 @@
import path from "path";
import { loadEnv } from "vite";
import istanbul from "vite-plugin-istanbul";
import svgr from "vite-plugin-svgr";
import { defineConfig } from "vite-react";
import tsconfigPaths from "vite-tsconfig-paths";
const isCoverage = process.env.VITE_COVERAGE === "true";
const istanbulPlugin = isCoverage
? istanbul({
include: "src/*",
exclude: ["node_modules"],
extension: [".js", ".jsx", ".ts", ".tsx"],
requireEnv: true,
})
: undefined;
const sourcemap = isCoverage ? "inline" : undefined;
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, "env");
function assetOutput(name: string | undefined) {
if (name && name.endsWith(".css")) {
return "static/css/[name].[hash].[ext]";
}
return "static/media/[name].[hash].[ext]";
}
return {
build: {
sourcemap,
outDir: "../internal/server/public_html",
assetsDir: "static",
rollupOptions: {
output: {
entryFileNames: `static/js/[name].[hash].js`,
chunkFileNames: `static/js/[name].[hash].js`,
assetFileNames: ({ name }) => assetOutput(name),
},
},
},
envDir: "env",
eslint: {
enable: true,
},
html: {
injectData: {
...env,
},
},
server: {
open: false,
hmr: {
clientPort: env.VITE_HMR_PORT || 3000,
},
},
resolve: {
alias: [
{
find: "@components",
replacement: path.resolve(__dirname, "src/components"),
},
],
},
plugins: [istanbulPlugin, svgr(), tsconfigPaths()],
};
});