Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
ahabhgk committed Sep 21, 2023
1 parent d6072e5 commit 25d0595
Show file tree
Hide file tree
Showing 41 changed files with 764 additions and 18 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/rspack_binding_options/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_identifier = { path = "../rspack_identifier" }
rspack_ids = { path = "../rspack_ids" }
rspack_loader_react_refresh = { path = "../rspack_loader_react_refresh" }
rspack_loader_runner = { path = "../rspack_loader_runner" }
rspack_loader_sass = { path = "../rspack_loader_sass" }
rspack_loader_swc = { path = "../rspack_loader_swc" }
Expand Down
6 changes: 6 additions & 0 deletions crates/rspack_binding_options/src/options/raw_module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use rspack_core::{
ModuleRuleUseLoader, ModuleType, ParserOptions, ParserOptionsByModuleType,
};
use rspack_error::internal_error;
use rspack_loader_react_refresh::REACT_REFRESH_LOADER_IDENTIFIER;
use rspack_loader_sass::SASS_LOADER_IDENTIFIER;
use rspack_loader_swc::SWC_LOADER_IDENTIFIER;
use serde::Deserialize;
Expand Down Expand Up @@ -44,6 +45,11 @@ pub fn get_builtin_loader(builtin: &str, options: Option<&str>) -> BoxLoader {
.with_identifier(builtin.into()),
);
}
if builtin.starts_with(REACT_REFRESH_LOADER_IDENTIFIER) {
return Arc::new(
rspack_loader_react_refresh::ReactRefreshLoader::new().with_identifier(builtin.into()),
);
}

unreachable!("Unexpected builtin loader: {builtin}")
}
Expand Down
14 changes: 14 additions & 0 deletions crates/rspack_loader_react_refresh/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
edition = "2021"
license = "MIT"
name = "rspack_loader_react_refresh"
repository = "https://github.com/web-infra-dev/rspack"
version = "0.1.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
async-trait = { workspace = true }
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_loader_runner = { path = "../rspack_loader_runner" }
22 changes: 22 additions & 0 deletions crates/rspack_loader_react_refresh/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2022-present Bytedance, Inc. and its affiliates.


Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
51 changes: 51 additions & 0 deletions crates/rspack_loader_react_refresh/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use rspack_core::LoaderRunnerContext;
use rspack_error::{internal_error, Result};
use rspack_loader_runner::{Identifiable, Identifier, Loader, LoaderContext};

pub struct ReactRefreshLoader {
identifier: Identifier,
}

impl ReactRefreshLoader {
pub fn new() -> Self {

Check failure on line 10 in crates/rspack_loader_react_refresh/src/lib.rs

View workflow job for this annotation

GitHub Actions / Rust check

you should consider adding a `Default` implementation for `ReactRefreshLoader`
Self {
identifier: REACT_REFRESH_LOADER_IDENTIFIER.into(),
}
}

/// Panics:
/// Panics if `identifier` passed in is not starting with `builtin:react-refresh-loader`.
pub fn with_identifier(mut self, identifier: Identifier) -> Self {
assert!(identifier.starts_with(REACT_REFRESH_LOADER_IDENTIFIER));
self.identifier = identifier;
self
}
}

#[async_trait::async_trait]
impl Loader<LoaderRunnerContext> for ReactRefreshLoader {
async fn run(&self, loader_context: &mut LoaderContext<'_, LoaderRunnerContext>) -> Result<()> {
let Some(content) = std::mem::take(&mut loader_context.content) else {
return Err(internal_error!("Content should be available"))
};
let mut source = content.try_into_string()?;
source += r#"
function $RefreshReg$(type, id) {
$ReactRefreshRuntime$.register(type, __webpack_module__.id + "_" + id);
}
Promise.resolve().then(function() {
$ReactRefreshRuntime$.refresh(__webpack_module__.id, __webpack_module__.hot);
});
"#;
loader_context.content = Some(source.into());
Ok(())
}
}

pub const REACT_REFRESH_LOADER_IDENTIFIER: &str = "builtin:react-refresh-loader";

impl Identifiable for ReactRefreshLoader {
fn identifier(&self) -> Identifier {
self.identifier
}
}
10 changes: 7 additions & 3 deletions examples/react-refresh/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@
"private": true,
"scripts": {
"dev": "rspack serve ",
"build": "rspack build"
"build": "cross-env NODE_ENV=production rspack build"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@rspack/cli": "workspace:*",
"react": "18.0.0",
"react-dom": "18.0.0",
"react-dom": "18.0.0"
},
"devDependencies": {
"@rspack/cli": "workspace:*",
"@rspack/core": "workspace:*",
"@rspack/plugin-react-refresh": "workspace:*",
"react-refresh": "0.13.0"
}
}
55 changes: 45 additions & 10 deletions examples/react-refresh/rspack.config.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,49 @@
/**
* @type {import('@rspack/cli').Configuration}
*/
const rspack = require("@rspack/core")
const ReactRefreshPlugin = require("@rspack/plugin-react-refresh")

const isProduction = process.env.NODE_ENV === "production"

/** @type {import('@rspack/cli').Configuration} */
const config = {
mode: "development",
entry: { main: "./src/index.tsx" },
builtins: {
html: [{ template: "./index.html" }],
define: {
"process.env.NODE_ENV": "'development'"
experiments: {
rspackFuture: {
disableTransformByDefault: true,
}
}
},
mode: isProduction ? "production" : "development",
entry: { main: "./src/index.tsx" },
devtool: 'source-map',
module: {
rules: [
{
test: /\.tsx$/,
use: {
loader: "builtin:swc-loader",
options: {
sourceMap: true,
jsc: {
parser: {
syntax: "typescript",
tsx: true
},
transform: {
react: {
runtime: "automatic",
development: !isProduction,
refresh: !isProduction,
}
}
}
}
}
}
]
},
plugins: [
new rspack.HtmlRspackPlugin({ template: "./index.html" }),
new rspack.DefinePlugin({ "process.env.NODE_ENV": "'development'" }),
!isProduction && new ReactRefreshPlugin(),
].filter(Boolean)
};

module.exports = config;
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { test, expect } from "@/fixtures";

test("render should work", async ({ page }) => {
expect(await page.textContent(".header")).toBe("Hello World");
expect(await page.textContent("#lazy-component")).toBe("Lazy Component");
});

test("hmr should work", async ({ page, fileAction, rspack }) => {
expect(await page.textContent("button")).toBe("10");
await page.click("button");
expect(await page.textContent("button")).toBe("11");
expect(await page.textContent(".placeholder")).toBe("__PLACE_HOLDER__");
fileAction.updateFile("src/App.jsx", content =>
content.replace("__PLACE_HOLDER__", "__EDITED__")
);
await rspack.waitingForHmr(async function () {
return (await page.textContent(".placeholder")) === "__EDITED__";
});
expect(await page.textContent("button")).toBe("11");
});

test("context+component should work", async ({ page, fileAction, rspack }) => {
expect(await page.textContent("#context")).toBe("context-value");
await page.click("#context");
expect(await page.textContent("#context")).toBe("context-value-click");
fileAction.updateFile("src/CountProvider.jsx", content =>
content.replace("context-value", "context-value-update")
);
await rspack.waitingForHmr(async function () {
return (await page.textContent("#context")) === "context-value-update";
});
});

test("ReactRefreshFinder should work", async ({ page }) => {
expect(await page.textContent("#nest-function")).toBe("nest-function");
});

test("update same export name from different module should work", async ({
page,
fileAction,
rspack
}) => {
expect(await page.textContent(".same-export-name1")).toBe("__NAME_1__");
expect(await page.textContent(".same-export-name2")).toBe("__NAME_2__");
fileAction.updateFile("src/SameExportName1.jsx", content =>
content.replace("__NAME_1__", "__name_1__")
);
await rspack.waitingForHmr(async function () {
return (await page.textContent(".same-export-name1")) === "__name_1__";
});
expect(await page.textContent(".same-export-name2")).toBe("__NAME_2__");
fileAction.updateFile("src/SameExportName2.jsx", content =>
content.replace("__NAME_2__", "__name_2__")
);
await rspack.waitingForHmr(async function () {
return (await page.textContent(".same-export-name2")) === "__name_2__";
});
expect(await page.textContent(".same-export-name1")).toBe("__name_1__");
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const rspack = require("@rspack/core");
const ReactRefreshPlugin = require("@rspack/plugin-react-refresh");

/** @type { import('@rspack/core').RspackOptions } */
module.exports = {
experiments: {
rspackFuture: {
disableTransformByDefault: true
}
},
context: __dirname,
mode: "development",
module: {
rules: [
{
test: /\.jsx$/,
use: {
loader: "builtin:swc-loader",
options: {
jsc: {
parser: {
syntax: "ecmascript",
jsx: true
},
transform: {
react: {
runtime: "automatic",
development: true,
refresh: true
}
}
}
}
}
}
]
},
plugins: [
new rspack.HtmlRspackPlugin({ template: "./src/index.html" }),
new ReactRefreshPlugin()
],
entry: "./src/index.jsx",
devServer: {
hot: true,
devMiddleware: {
writeToDisk: true
}
},
cache: false,
stats: "none",
infrastructureLogging: {
debug: false
},
watchOptions: {
poll: 1000
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React from 'react'
import './index.css'
import { ContextComponent } from './CountProvider'
import { ReactRefreshFinder } from './ReactRefreshFinder'
import { SameExportName as SameExportName1 } from './SameExportName1'
import { SameExportName as SameExportName2 } from './SameExportName2'

const Button = () => {
const [count, setCount] = React.useState(10)
return <button onClick={() => setCount(count => count + 1)}>{count}</button>
}

const LazyComponent = React.lazy(() => import('./LazyComponent'))

export const App = () => {
return (
<div className='App'>
<div className='header'>Hello World</div>
<Button />
<div className='placeholder'>__PLACE_HOLDER__</div>
<ContextComponent />
<ReactRefreshFinder />
<SameExportName1 />
<SameExportName2 />
<React.Suspense fallback={<div>loading...</div>}>
<LazyComponent />
</React.Suspense>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from 'react';

export const CountContext = React.createContext();

export function CountProvider({ children }) {
const [count, setCount] = React.useState('context-value');
return (
<CountContext.Provider value={{ count, setCount }}>
{children}
</CountContext.Provider>
);
}

export function ContextComponent() {
const { count, setCount } = React.useContext(CountContext);
return <div id="context" onClick={() => setCount((count) => count + '-click')}>
{count}
</div>
}
Empty file.
Loading

0 comments on commit 25d0595

Please sign in to comment.