refactor(web): migrate create-react-app to vite (#823)

* fix(build): dockerignore add exclusions

* fix: baseurl and build

* chore: removed react-app-env instead use vite

* chore: updated server and embedding static files.

* commented because conflict I believe, and not needed.

* docs: updated readme

* chore: updated json and added vite

* chore: import fix

* chore: updated yarn.lock and package json

* build: add empty dist to compile backend

* fix: use / as default baseurl

---------

Co-authored-by: KaiserBh <kaiserbh@proton.me>
Co-authored-by: ze0s <ze0s@riseup.net>
This commit is contained in:
KaiserBh 2023-04-10 22:28:24 +10:00 committed by GitHub
parent 33897b04a1
commit 1cdbbe5bf3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 717 additions and 9474 deletions

View file

@ -15,7 +15,7 @@ test
web/*
!web/public
!web/src
!web/build*
!web/dist*
!web/package.json
!web/yarn.lock
!web/.yarnrc.yml
@ -24,3 +24,6 @@ web/*
!web/postcss.config.js
!web/tailwind.config.js
!web/tsconfig.json
!web/index.html
!web/vite.config.ts
!web/build.go

View file

@ -38,8 +38,8 @@ jobs:
- name: Upload web production build
uses: actions/upload-artifact@v3
with:
name: web-build
path: web/build
name: web-dist
path: web/dist
test:
name: Test
@ -54,8 +54,8 @@ jobs:
- name: Download web production build
uses: actions/download-artifact@v3
with:
name: web-build
path: web/build
name: web-dist
path: web/dist
# 1.20 is the last version to support Windows < 10, Server < 2016, and MacOS < 1.15.
- name: Set up Go
@ -81,8 +81,8 @@ jobs:
- name: Download web production build
uses: actions/download-artifact@v3
with:
name: web-build
path: web/build
name: web-dist
path: web/dist
# 1.20 is the last version to support Windows < 10, Server < 2016, and MacOS < 1.15.
- name: Set up Go
@ -120,8 +120,8 @@ jobs:
- name: Download web production build
uses: actions/download-artifact@v3
with:
name: web-build
path: web/build
name: web-dist
path: web/dist
# 1.20 is the last version to support Windows < 10, Server < 2016, and MacOS < 1.15.
- name: Set up Go
@ -158,8 +158,8 @@ jobs:
- name: Download web production build
uses: actions/download-artifact@v3
with:
name: web-build
path: web/build
name: web-dist
path: web/dist
- name: Login to GitHub Container Registry
uses: docker/login-action@v2

2
.gitignore vendored
View file

@ -31,7 +31,7 @@ node_modules/
web/build
bin/
log/
dist/
#dist/
.run/
# If needed, package-lock.json shall be added
# manually using an explicit git add command.

View file

@ -25,7 +25,7 @@ RUN go mod download
COPY . ./
COPY --from=web-builder /web/build ./web/build
COPY --from=web-builder /web/dist ./web/dist
COPY --from=web-builder /web/build.go ./web
#ENV GOOS=linux

View file

@ -2,7 +2,6 @@ package http
import (
"fmt"
"io/fs"
"net"
"net/http"
@ -105,18 +104,8 @@ func (s Server) Handler() http.Handler {
r.Use(c.Handler)
//r.Get("/", index)
//r.Get("/dashboard", dashboard)
//handler := web.AssetHandler("/", "build")
encoder := encoder{}
assets, _ := fs.Sub(web.Assets, "build/static")
r.HandleFunc("/static/*", func(w http.ResponseWriter, r *http.Request) {
fileSystem := http.StripPrefix("/static/", http.FileServer(http.FS(assets)))
fileSystem.ServeHTTP(w, r)
})
web.RegisterHandler(r)
r.Route("/api", func(r chi.Router) {
r.Route("/auth", newAuthHandler(encoder, s.log, s.config.Config, s.cookieStore, s.authService).Routes)
@ -153,7 +142,7 @@ func (s Server) Handler() http.Handler {
})
})
//r.HandleFunc("/*", handler.ServeHTTP)
// serve the parsed index.html
r.Get("/", s.index)
r.Get("/*", s.index)

View file

@ -42,7 +42,7 @@ module.exports = {
//"plugin:@typescript-eslint/recommended-requiring-type-checking",
],
parserOptions: {
project: "tsconfig.json",
// project: "tsconfig.json",
// This is needed so we can always point to the tsconfig.json
// file relative to the current .eslintrc.js file.
// Generally, a problem occurrs when "npm run lint"

3
web/.gitignore vendored
View file

@ -31,7 +31,8 @@ node_modules/
web/build
bin/
log/
dist/
dist/*
!dist/.gitkeep
# If needed, package-lock.json shall be added
# manually using an explicit git add command.
package-lock.json

View file

@ -1,6 +1,6 @@
# Getting Started with Create React App
# web
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
This project uses React built with Vite.
## Available Scripts
@ -14,33 +14,14 @@ Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
Builds the app for production to the `dist` folder.\
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.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent 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 wouldnt be useful if you couldnt 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/).

View file

@ -2,47 +2,22 @@
package web
import (
"bytes"
"embed"
"fmt"
"html/template"
"io"
"io/fs"
"net/http"
"os"
"path"
"path/filepath"
"github.com/go-chi/chi/v5"
)
//go:embed build
var Assets embed.FS
// fsFunc is short-hand for constructing a http.FileSystem
// implementation
type fsFunc func(name string) (fs.File, error)
func (f fsFunc) Open(name string) (fs.File, error) {
return f(name)
}
// AssetHandler returns a http.Handler that will serve files from
// the Assets embed.FS. When locating a file, it will strip the given
// prefix from the request and prepend the root to the filesystem
// lookup: typical prefix might be /web/, and root would be build.
func AssetHandler(prefix, root string) http.Handler {
handler := fsFunc(func(name string) (fs.File, error) {
assetPath := path.Join(root, name)
// If we can't find the asset, return the default index.html
// content
f, err := Assets.Open(assetPath)
if os.IsNotExist(err) {
return Assets.Open("build/index.html")
}
// Otherwise, assume this is a legitimate request routed
// correctly
return f, err
})
return http.StripPrefix(prefix, http.FileServer(http.FS(handler)))
type defaultFS struct {
prefix string
fs fs.FS
}
type IndexParams struct {
@ -51,11 +26,109 @@ type IndexParams struct {
BaseUrl string
}
var (
//go:embed all:dist
Dist embed.FS
DistDirFS = MustSubFS(Dist, "dist")
)
func (fs defaultFS) Open(name string) (fs.File, error) {
if fs.fs == nil {
return os.Open(name)
}
return fs.fs.Open(name)
}
// MustSubFS creates sub FS from current filesystem or panic on failure.
// Panic happens when `fsRoot` contains invalid path according to `fs.ValidPath` rules.
//
// MustSubFS is helpful when dealing with `embed.FS` because for example `//go:embed assets/images` embeds files with
// paths including `assets/images` as their prefix. In that case use `fs := MustSubFS(fs, "rootDirectory") to
// create sub fs which uses necessary prefix for directory path.
func MustSubFS(currentFs fs.FS, fsRoot string) fs.FS {
subFs, err := subFS(currentFs, fsRoot)
if err != nil {
panic(fmt.Errorf("can not create sub FS, invalid root given, err: %w", err))
}
return subFs
}
func subFS(currentFs fs.FS, root string) (fs.FS, error) {
root = filepath.ToSlash(filepath.Clean(root)) // note: fs.FS operates only with slashes. `ToSlash` is necessary for Windows
if dFS, ok := currentFs.(*defaultFS); ok {
// we need to make exception for `defaultFS` instances as it interprets root prefix differently from fs.FS.
// fs.Fs.Open does not like relative paths ("./", "../") and absolute paths.
if !filepath.IsAbs(root) {
root = filepath.Join(dFS.prefix, root)
}
return &defaultFS{
prefix: root,
fs: os.DirFS(root),
}, nil
}
return fs.Sub(currentFs, root)
}
// FileFS registers a new route with path to serve a file from the provided file system.
func FileFS(r *chi.Mux, path, file string, filesystem fs.FS) {
r.Get(path, StaticFileHandler(file, filesystem))
}
// StaticFileHandler creates a handler function to serve a file from the provided file system.
func StaticFileHandler(file string, filesystem fs.FS) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fsFile(w, r, file, filesystem)
}
}
// StaticFS registers a new route with path prefix to serve static files from the provided file system.
func StaticFS(r *chi.Mux, pathPrefix string, filesystem fs.FS) {
r.Handle(pathPrefix+"*", http.StripPrefix(pathPrefix, http.FileServer(http.FS(filesystem))))
}
// fsFile is a helper function to serve a file from the provided file system.
func fsFile(w http.ResponseWriter, r *http.Request, file string, filesystem fs.FS) {
f, err := filesystem.Open(file)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
data, err := io.ReadAll(f)
if err != nil {
http.Error(w, "Failed to read the file", http.StatusInternalServerError)
return
}
reader := bytes.NewReader(data)
http.ServeContent(w, r, file, stat.ModTime(), reader)
}
func RegisterHandler(c *chi.Mux) {
// Serve static files without a prefix
assets, _ := fs.Sub(DistDirFS, "assets")
static, _ := fs.Sub(DistDirFS, "static")
StaticFS(c, "/assets", assets)
StaticFS(c, "/static", static)
c.Get("/*", func(w http.ResponseWriter, r *http.Request) {
// Serve index.html for unmatched routes
fsFile(w, r, "dist/index.html", Dist)
})
}
func Index(w io.Writer, p IndexParams) error {
return parseIndex().Execute(w, p)
}
func parseIndex() *template.Template {
return template.Must(
template.New("index.html").ParseFS(Assets, "build/index.html"))
return template.Must(template.New("index.html").ParseFS(Dist, "dist/index.html"))
}

0
web/dist/.gitkeep vendored Normal file
View file

View file

@ -2,32 +2,25 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/static/favicon.ico" />
<link rel="icon" href="/static/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="autobrr"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/static/logo192.png" />
<link crossorigin="use-credentials" rel="manifest" href="%PUBLIC_URL%/static/manifest.json" />
<link rel="apple-touch-icon" href="/static/logo192.png" />
<link crossorigin="use-credentials" rel="manifest" href="/static/manifest.json" />
<title>autobrr</title>
<!-- {{if eq .BaseUrl "/" }}
<base href="%PUBLIC_URL%/">
<script>
window.APP = {}
window.APP.baseUrl = "/"
</script>
{{else}} -->
<base href="{{.BaseUrl}}">
<script>
window.APP = {}
window.APP.baseUrl = "{{.BaseUrl}}"
</script>
<!-- {{end}} -->
</head>
<body class="bg-color">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root" class="pattern"></div>
<script type="module" src="./src/index.tsx"></script>
</body>
</html>

View file

@ -24,16 +24,15 @@
"react-query": "^3.39.1",
"react-ridge-state": "4.2.2",
"react-router-dom": "^6.3.0",
"react-scripts": "^5.0.1",
"react-select": "^5.3.2",
"react-table": "^7.8.0",
"react-tooltip": "^5.5.2",
"stacktracey": "^2.1.8"
},
"scripts": {
"start": "BROWSER=none react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"start": "vite",
"build": "tsc && vite build",
"serve": "vite preview",
"lint": "eslint src/ --ext .js,.jsx,.ts,.tsx --color",
"lint:watch": "npm run lint -- --watch"
},
@ -58,6 +57,7 @@
"@types/react-table": "^7.7.12",
"@typescript-eslint/eslint-plugin": "^5.28.0",
"@typescript-eslint/parser": "^5.28.0",
"@vitejs/plugin-react-swc": "^3.2.0",
"autoprefixer": "^10.4.7",
"eslint": "^8.17.0",
"eslint-plugin-import": "^2.26.0",
@ -67,7 +67,8 @@
"http-proxy-middleware": "^2.0.6",
"postcss": "^8.4.14",
"tailwindcss": "^3.1.3",
"typescript": "^4.7.3"
"typescript": "^4.7.3",
"vite": "^4.2.1"
},
"packageManager": "yarn@3.2.2"
}

View file

@ -1,6 +1,8 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
"postcss-import": {},
"tailwindcss/nesting": {},
tailwindcss: {},
autoprefixer: {},
}
}
}

View file

@ -19,7 +19,7 @@ import {
LogSettings,
NotificationSettings,
ReleaseSettings
} from "../screens/settings/";
} from "../screens/settings/index";
import { RegexPlayground } from "../screens/settings/RegexPlayground";
import { baseUrl } from "../utils";

View file

@ -1 +0,0 @@
/// <reference types="react-scripts" />

View file

@ -9,17 +9,12 @@ export function sleep(ms: number) {
export function baseUrl() {
let baseUrl = "";
if (window.APP.baseUrl) {
if (window.APP.baseUrl === "/") {
if (window.APP.baseUrl === "{{.BaseUrl}}") {
baseUrl = "/";
} else if (window.APP.baseUrl === "{{.BaseUrl}}") {
baseUrl = "/";
} else if (window.APP.baseUrl === "/autobrr/") {
baseUrl = "/autobrr/";
} else {
baseUrl = window.APP.baseUrl;
}
}
return baseUrl;
}

1
web/src/vite-env.d.ts vendored Normal file
View file

@ -0,0 +1 @@
/// <reference types="vite/client" />

View file

@ -6,9 +6,9 @@
"DOM.Iterable",
"ESNext"
],
"types": [],
"types": ["vite/client"],
"allowJs": false,
"skipLibCheck": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
@ -19,10 +19,14 @@
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noFallthroughCasesInSwitch": true
"noFallthroughCasesInSwitch": true,
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"./src",
"./types"
]
"./types",
"vite.config.ts"
],
}

37
web/vite.config.ts Normal file
View file

@ -0,0 +1,37 @@
import { fileURLToPath, URL } from "node:url";
import react from "@vitejs/plugin-react-swc";
import { defineConfig, loadEnv } from "vite";
// https://vitejs.dev/config/
export default ({ mode }: { mode: any }) => {
// early load .env file
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
// import.meta.env.VITE_NAME available here with: process.env.VITE_NAME
return defineConfig({
base: "",
plugins: [react()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url))
}
},
server: {
port: 3000,
hmr: {
overlay: true
},
proxy: {
"/api": {
target: "http://127.0.0.1:7474/",
changeOrigin: true,
secure: false
}
}
},
build: {
manifest: true,
sourcemap: true
}
});
};

File diff suppressed because it is too large Load diff