Skip to content

Commit

Permalink
Switch to rspack
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiask committed Sep 6, 2024
1 parent 0cdc0a6 commit db75eac
Show file tree
Hide file tree
Showing 8 changed files with 2,618 additions and 165 deletions.
1 change: 0 additions & 1 deletion app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
STATICFILES_DIRS = [
# BASE_DIR / "frontend" / "static"
]
WEBPACK_ASSETS = BASE_DIR / "static"

STORAGES = {
"default": django_storage_url(
Expand Down
14 changes: 4 additions & 10 deletions app/templatetags/webpack_assets.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from functools import cache
from pathlib import Path

from django import template
from django.conf import settings
Expand All @@ -9,16 +8,11 @@
register = template.Library()


def webpack_assets(entry): # pragma: no cover
base = Path.cwd()
if settings.DEBUG:
base = base / "tmp" / "dev"
assets = (base / "static" / f"{entry}.html").read_text()
for part in ("<head>", "</head>", "<title></title>"):
assets = assets.replace(part, "")
return mark_safe(assets)
def webpack_assets(entry):
path = settings.BASE_DIR / ("tmp" if settings.DEBUG else "static") / f"{entry}.html"
return mark_safe(path.read_text())


if not settings.DEBUG: # pragma: no branch
if not settings.DEBUG:
webpack_assets = cache(webpack_assets)
register.simple_tag(webpack_assets)
13 changes: 1 addition & 12 deletions fabfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,4 @@
)


@fl.task(auto_shortflags=False)
def dev(ctx, host="127.0.0.1", port=8000):
fl._concurrently(
ctx,
[
f".venv/bin/python manage.py runserver 0.0.0.0:{port}",
f"yarn run rsbuild dev --host {host}",
],
)


ns = fl.Collection(*fl.GENERAL, dev)
ns = fl.Collection(*fl.GENERAL)
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@
"semi": false
},
"dependencies": {
"@rsbuild/core": "^1.0.1-rc.3",
"@rspack/cli": "^1.0.3",
"@rspack/core": "^1.0.3",
"@swc/helpers": "^0.5.13",
"autoprefixer": "^10.4.20",
"babel-loader": "^9.1.3",
"core-js": "^3.38.1",
"html-webpack-plugin": "^5.6.0",
"postcss": "^8.4.45",
"postcss-loader": "^8.1.1",
"postcss-nesting": "^13.0.0"
}
}
48 changes: 0 additions & 48 deletions rsbuild.config.ts

This file was deleted.

18 changes: 18 additions & 0 deletions rspack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = (env, argv) => {
const { base, devServer, assetRule, postcssRule, swcWithPreactRule } =
require("./rspack.library.js")(argv.mode === "production")

return {
...base,
devServer: devServer({ backendPort: env.backend }),
module: {
rules: [
assetRule(),
postcssRule({
plugins: ["postcss-nesting", "autoprefixer"],
}),
swcWithPreactRule(),
],
},
}
}
224 changes: 224 additions & 0 deletions rspack.library.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
/*
Somewhat reusable webpack configuration chunks
A basic rspack file may looks as follows:
module.exports = (env, argv) => {
const {
base,
devServer,
assetRule,
postcssRule,
swcWithPreactRule,
resolvePreactAsReact,
} = require("./rspack.library.js")(argv.mode === "production")
return {
...base,
...resolvePreactAsReact(),
devServer: devServer({ backendPort: env.backend }),
module: {
rules: [
assetRule(),
postcssRule({
plugins: [
[
"@csstools/postcss-global-data",
{ files: ["./frontend/styles/custom-media.css"] },
],
"postcss-custom-media",
"postcss-nesting",
"autoprefixer",
],
}),
swcWithPreactRule(),
],
},
}
}
NOTE: PLEASE DO NOT EVER UPDATE THIS FILE WITHOUT CONTRIBUTING THE CHANGES BACK
TO FH-FABLIB AT https://github.com/feinheit/fh-fablib
*/

const path = require("node:path")
const HtmlWebpackPlugin = require("html-webpack-plugin")

const truthy = (...list) => list.filter((el) => !!el)

module.exports = (PRODUCTION) => {
const cwd = process.cwd()

function swcWithPreactRule() {
return {
test: /\.(j|t)sx?$/,
loader: "builtin:swc-loader",
exclude: [/[\\/]node_modules[\\/]|foundation/],
options: {
jsc: {
parser: {
syntax: "ecmascript",
jsx: true,
},
transform: {
react: {
runtime: "automatic",
importSource: "preact",
},
},
externalHelpers: true,
},
env: {
targets: "Chrome >= 48", // browser compatibility
},
},
type: "javascript/auto",
}
}

function swcWithReactRule() {
return {
test: /\.(j|t)sx?$/,
loader: "builtin:swc-loader",
exclude: [/[\\/]node_modules[\\/]|foundation/],
options: {
jsc: {
parser: {
syntax: "ecmascript",
jsx: true,
},
transform: {
react: {
runtime: "automatic",
// importSource: "preact",
},
},
externalHelpers: true,
},
env: {
targets: "Chrome >= 48", // browser compatibility
},
},
type: "javascript/auto",
}
}

function htmlPlugin(name = "", config = {}) {
return new HtmlWebpackPlugin({
filename: name ? `${name}.html` : "[name].html",
inject: false,
templateContent: ({ htmlWebpackPlugin }) =>
`${htmlWebpackPlugin.tags.headTags}`,
...config,
})
}

function htmlSingleChunkPlugin(chunk = "") {
return htmlPlugin(chunk, chunk ? { chunks: [chunk] } : {})
}

function postcssLoaders(plugins) {
return [
{ loader: "postcss-loader", options: { postcssOptions: { plugins } } },
]
}

return {
truthy,
base: {
// mode: PRODUCTION ? "production" : "development",
// bail: PRODUCTION,
context: path.join(cwd, "frontend"),
entry: { main: "./main.js" },
output: {
clean: PRODUCTION,
path: path.join(cwd, PRODUCTION ? "static" : "tmp"),
publicPath: "/static/",
filename: PRODUCTION ? "[name].[contenthash].js" : "[name].js",
// Same as the default but prefixed with "_/[name]."
assetModuleFilename: "_/[name].[hash][ext][query][fragment]",
},
plugins: truthy(htmlSingleChunkPlugin()),
experiments: { css: true },
},
devServer(proxySettings) {
return {
host: "0.0.0.0",
hot: true,
port: Number(process.env.PORT || 4000),
allowedHosts: "all",
client: {
overlay: {
errors: true,
warnings: false,
runtimeErrors: true,
},
},
devMiddleware: {
headers: { "Access-Control-Allow-Origin": "*" },
index: true,
writeToDisk: (path) => /\.html$/.test(path),
},
proxy: [
proxySettings
? {
context: () => true,
target: `http://127.0.0.1:${proxySettings.backendPort}`,
}
: {},
],
}
},
assetRule() {
return {
test: /\.(png|woff2?|svg|eot|ttf|otf|gif|jpe?g|mp3|wav)$/i,
type: "asset",
parser: { dataUrlCondition: { maxSize: 512 /* bytes */ } },
}
},
postcssRule(cfg) {
return {
test: /\.css$/i,
type: "css",
use: postcssLoaders(cfg?.plugins),
}
},
sassRule(options = {}) {
let { cssLoaders } = options
if (!cssLoaders) cssLoaders = postcssLoaders(["autoprefixer"])
return {
test: /\.scss$/i,
use: [
...cssLoaders,
{
loader: "sass-loader",
options: {
sassOptions: {
includePaths: [path.resolve(path.join(cwd, "node_modules"))],
},
},
},
],
type: "css",
}
},
swcWithPreactRule,
swcWithReactRule,
resolvePreactAsReact() {
return {
resolve: {
alias: {
react: "preact/compat",
"react-dom/test-utils": "preact/test-utils",
"react-dom": "preact/compat", // Must be below test-utils
"react/jsx-runtime": "preact/jsx-runtime",
},
},
}
},
htmlPlugin,
htmlSingleChunkPlugin,
postcssLoaders,
}
}
Loading

0 comments on commit db75eac

Please sign in to comment.