Migrate to webpack

This commit is contained in:
Edward Shen 2022-01-18 01:39:56 -08:00
parent 08f3e940e4
commit 6859bffe05
Signed by: edward
GPG key ID: 19182661E818369F
19 changed files with 1433 additions and 3449 deletions

1
.gitignore vendored
View file

@ -5,3 +5,4 @@
test.* test.*
dist.tar.zst dist.tar.zst
.env .env
web/pkg

View file

@ -1,17 +0,0 @@
[build]
target = "web/index.html"
release = true
dist = "./dist"
[clean]
dist = "./dist"
[[proxy]]
backend = "http://localhost:8081"
rewrite = "/api/"
[[hooks]]
stage="post_build"
command="npx"
command_arguments=["swc", "$TRUNK_SOURCE_DIR/src/main.ts", "-o", "$TRUNK_STAGING_DIR/main.js"]

View file

@ -22,10 +22,9 @@ cd "$(git rev-parse --show-toplevel)" || exit 1
# Build frontend assets # Build frontend assets
yarn yarn
trunk build --release
sed -i 's#/index#/static/index#g' dist/index.html rm -rf dist
sed -i 's#stylesheet" href="/main#stylesheet" href="/static/main#g' dist/index.html yarn webpack
# Build server # Build server
cargo build --release --bin omegaupload-server cargo build --release --bin omegaupload-server

View file

@ -19,17 +19,9 @@
set -euxo pipefail set -euxo pipefail
CUR_DIR=$(pwd) CUR_DIR=$(pwd)
PROJECT_TOP_LEVEL=$(git rev-parse --show-toplevel) PROJECT_TOP_LEVEL=$(git rev-parse --show-toplevel)
cd "$PROJECT_TOP_LEVEL" || exit 1 cd "$PROJECT_TOP_LEVEL" || exit 1
git submodule foreach git pull git submodule foreach git pull
HLJS_PATH=$(git submodule status | cut -d ' ' -f3 | grep highlight.js)
cd "$HLJS_PATH"
npm ci # install without updating package-lock.josn
node tools/build
mv build/highlight.min.js "$PROJECT_TOP_LEVEL"/"$HLJS_PATH"/..
cd "$CUR_DIR" cd "$CUR_DIR"

View file

@ -1,6 +1,19 @@
{ {
"devDependencies": { "devDependencies": {
"@swc/cli": "^0.1.51", "@swc/cli": "^0.1.51",
"@swc/core": "^1.2.102" "@swc/core": "^1.2.102",
"@wasm-tool/wasm-pack-plugin": "^1.6.0",
"css-loader": "^6.5.1",
"html-webpack-plugin": "^5.5.0",
"sass": "^1.48.0",
"sass-loader": "^12.4.0",
"style-loader": "^3.3.1",
"swc-loader": "^0.1.15",
"webpack": "^5.66.0",
"webpack-cli": "^4.9.1"
},
"dependencies": {
"highlight.js": "^11.4.0",
"highlightjs-line-numbers.js": "^2.8.0"
} }
} }

View file

@ -26,7 +26,6 @@ use axum::error_handling::HandleError;
use axum::extract::{Extension, Path, TypedHeader}; use axum::extract::{Extension, Path, TypedHeader};
use axum::http::header::EXPIRES; use axum::http::header::EXPIRES;
use axum::http::StatusCode; use axum::http::StatusCode;
use axum::response::Html;
use axum::routing::{get, get_service, post}; use axum::routing::{get, get_service, post};
use axum::{AddExtensionLayer, Router}; use axum::{AddExtensionLayer, Router};
use chrono::Utc; use chrono::Utc;
@ -41,7 +40,7 @@ use rocksdb::{Options, DB};
use signal_hook::consts::SIGUSR1; use signal_hook::consts::SIGUSR1;
use signal_hook_tokio::Signals; use signal_hook_tokio::Signals;
use tokio::task::{self, JoinHandle}; use tokio::task::{self, JoinHandle};
use tower_http::services::ServeDir; use tower_http::services::{ServeDir, ServeFile};
use tracing::{error, instrument, trace}; use tracing::{error, instrument, trace};
use tracing::{info, warn}; use tracing::{info, warn};
@ -58,7 +57,6 @@ lazy_static! {
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
const INDEX_PAGE: Html<&'static str> = Html(include_str!("../../dist/index.html"));
const PASTE_DB_PATH: &str = "database"; const PASTE_DB_PATH: &str = "database";
const SHORT_CODE_SIZE: usize = 12; const SHORT_CODE_SIZE: usize = 12;
@ -87,15 +85,19 @@ async fn main() -> Result<()> {
Ok::<_, Infallible>(StatusCode::NOT_FOUND) Ok::<_, Infallible>(StatusCode::NOT_FOUND)
}); });
let index_service = HandleError::new(get_service(ServeFile::new("index.html")), |_| async {
Ok::<_, Infallible>(StatusCode::NOT_FOUND)
});
axum::Server::bind(&"0.0.0.0:8080".parse()?) axum::Server::bind(&"0.0.0.0:8080".parse()?)
.serve({ .serve({
info!("Now serving on 0.0.0.0:8080"); info!("Now serving on 0.0.0.0:8080");
Router::new() Router::new()
.route( .route(
"/", "/",
post(upload::<SHORT_CODE_SIZE>).get(|| async { INDEX_PAGE }), post(upload::<SHORT_CODE_SIZE>).get_service(index_service.clone()),
) )
.route("/:code", get(|| async { INDEX_PAGE })) .route("/:code", index_service)
.nest("/static", root_service) .nest("/static", root_service)
.route( .route(
&format!("{API_ENDPOINT}/:code"), &format!("{API_ENDPOINT}/:code"),

View file

@ -3,7 +3,8 @@ name = "omegaupload-web"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib]
crate-type = ["cdylib"]
[dependencies] [dependencies]
omegaupload-common = { path = "../common", features = ["wasm"] } omegaupload-common = { path = "../common", features = ["wasm"] }

View file

@ -1,22 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Omegaupload</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="static/main.js" defer></script>
<script src="static/highlight.min.js" defer></script>
<script src="static/highlightjs-line-numbers.min.js" defer></script>
<link data-trunk rel="rust" data-wasm-opt="0" data-keep-debug="true" data-no-mangle="true" />
<link data-trunk rel="copy-file" href="vendor/MPLUS_FONTS/fonts/ttf/MPLUSCodeLatin[wdth,wght].ttf" dest="/" />
<link data-trunk rel="copy-file" href="vendor/highlight.min.js" dest="/" />
<link data-trunk rel="copy-file" href="vendor/highlightjs-line-numbers.js/dist/highlightjs-line-numbers.min.js"
dest="/" />
<link data-trunk rel="scss" href="src/main.scss" />
</head>
</html>

View file

@ -1 +0,0 @@
declare var hljs;

10
web/src/index.html Normal file
View file

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Omegaupload</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
</html>

3
web/src/index.js Normal file
View file

@ -0,0 +1,3 @@
import { start } from '../pkg';
start();

View file

@ -44,7 +44,7 @@ mod util;
const DOWNLOAD_SIZE_LIMIT: u128 = n_mib_bytes!(500); const DOWNLOAD_SIZE_LIMIT: u128 = n_mib_bytes!(500);
#[wasm_bindgen] #[wasm_bindgen(raw_module = "../src/render")]
extern "C" { extern "C" {
#[wasm_bindgen(js_name = loadFromDb)] #[wasm_bindgen(js_name = loadFromDb)]
pub fn load_from_db(mime_type: JsString, name: Option<JsString>, language: Option<JsString>); pub fn load_from_db(mime_type: JsString, name: Option<JsString>, language: Option<JsString>);
@ -69,7 +69,8 @@ fn open_idb() -> Result<IdbOpenDbRequest> {
.map_err(|_| anyhow!("Failed to open idb")) .map_err(|_| anyhow!("Failed to open idb"))
} }
fn main() { #[wasm_bindgen]
pub fn start() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook)); std::panic::set_hook(Box::new(console_error_panic_hook::hook));
if location().pathname().unwrap() == "/" { if location().pathname().unwrap() == "/" {

View file

@ -14,13 +14,13 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
@use '../vendor/highlight.js/src/styles/github-dark.css'; @use 'node_modules/highlight.js/styles/github-dark.css';
$padding: 1em; $padding: 1em;
@font-face { @font-face {
font-family: "Mplus Code"; font-family: "Mplus Code";
src: url("./MPLUSCodeLatin[wdth,wght].ttf") format("truetype"); src: url("../vendor/MPLUS_FONTS/fonts/ttf/MPLUSCodeLatin[wdth,wght].ttf") format("truetype");
} }
body { body {

View file

@ -14,7 +14,12 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
// Exported to main.rs import './main.scss';
const hljs = require('highlight.js');
window.hljs = hljs;
require('highlightjs-line-numbers.js');
function loadFromDb(mimeType: string, name?: string, language?: string) { function loadFromDb(mimeType: string, name?: string, language?: string) {
let resolvedName; let resolvedName;
if (name) { if (name) {
@ -167,7 +172,9 @@ function createStringPasteUi(data, mimeType: string, name: string, lang?: string
} }
hljs.highlightAll(); hljs.highlightAll();
hljs.initLineNumbersOnLoad();
(hljs as any).initLineNumbersOnLoad();
} }
function createBlobPasteUi(data, name: string) { function createBlobPasteUi(data, name: string) {
@ -340,3 +347,5 @@ function getObjectUrl(data, mimeType?: string) {
} }
window.addEventListener("hashchange", () => location.reload()); window.addEventListener("hashchange", () => location.reload());
export { renderMessage, loadFromDb };

@ -1 +0,0 @@
Subproject commit 112135fb063af64b7a94155b5d86859e8d52b6f0

File diff suppressed because one or more lines are too long

@ -1 +0,0 @@
Subproject commit c2d9209ce356956b86316da3881b125539a2aaa3

49
webpack.config.js Normal file
View file

@ -0,0 +1,49 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = {
entry: './web/src/index.js',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'swc-loader',
exclude: /node_modules/,
},
{
test: /\.scss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'web/src/index.html'),
publicPath: "/static",
}),
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, "web"),
outDir: path.resolve(__dirname, "web/pkg"),
}),
],
experiments: {
asyncWebAssembly: true,
},
mode: 'development'
};

1333
yarn.lock

File diff suppressed because it is too large Load diff