Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(diagnostic): improve diagnostics for swc wasm plugins when mismatch #8001

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ rspack_dojang = { version = "0.1.9" }
rate-limit = { existing-packages = 70, new-packages = 70 }
[profile.dev]
codegen-units = 16
debug = 2 # debug build will cause runtime panic if codegen-unints is default
SyMind marked this conversation as resolved.
Show resolved Hide resolved
debug = 2 # debug build will cause runtime panic if codegen-unints is default
incremental = true
panic = "abort"

Expand Down
4 changes: 2 additions & 2 deletions crates/rspack_error/src/miette_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ impl miette::Diagnostic for WithHelp {
fn help<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
let help = self.wrap_help.get_or_init(|| {
let prev = self.err.help().map(|h| h.to_string());
let help = self.help.as_ref().cloned();
let help = self.help.as_ref();
if let Some(prev) = prev {
if let Some(help) = &help {
Some(format!("{prev}\n{help}").into())
} else {
Some(prev.into())
}
} else if help.is_some() {
help
help.cloned()
} else {
None
}
Expand Down
3 changes: 3 additions & 0 deletions crates/rspack_loader_swc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ swc_core = { workspace = true, features = ["base", "ecma_ast", "
swc_plugin_import = { version = "0.1.5", path = "../swc_plugin_import" }
tokio = { workspace = true }
url = "2.5.0"

[build-dependencies]
cargo_toml = { version = "0.20.4" }
18 changes: 18 additions & 0 deletions crates/rspack_loader_swc/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
fn main() {
const CARGO_TOML: &str = include_str!("../../Cargo.toml");
let workspace_toml = cargo_toml::Manifest::from_str(CARGO_TOML)
.expect("Should parse cargo toml")
.workspace;
let swc_core_version = workspace_toml
.as_ref()
.and_then(|ws| {
ws.dependencies.get("swc_core").and_then(|dep| match dep {
cargo_toml::Dependency::Simple(s) => Some(&**s),
cargo_toml::Dependency::Inherited(_) => unreachable!(),
cargo_toml::Dependency::Detailed(d) => d.version.as_deref(),
})
})
.expect("Should have `swc_core` version")
.to_owned();
println!("cargo::rustc-env=RSPACK_SWC_CORE_VERSION={swc_core_version}");
}
32 changes: 31 additions & 1 deletion crates/rspack_loader_swc/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ use base64::prelude::*;
use dashmap::DashMap;
use jsonc_parser::parse_to_serde_value;
use rspack_ast::javascript::{Ast as JsAst, Context as JsAstContext, Program as JsProgram};
use rspack_error::miette::MietteDiagnostic;
use rspack_error::DiagnosticExt;
use rspack_util::itoa;
use serde_json::error::Category;
use swc_config::config_types::BoolOr;
Expand Down Expand Up @@ -390,7 +392,35 @@ impl SwcCompiler {
try_with_handler(self.cm.clone(), Default::default(), |handler| {
HANDLER.set(handler, || {
// Fold module
Ok(program.fold_with(&mut pass))
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
program.fold_with(&mut pass)
})) {
Ok(v) => Ok(v),
Err(err) => {
macro_rules! swc_error {
($tt:tt) => {{
let swc_core_version = env!("RSPACK_SWC_CORE_VERSION");

MietteDiagnostic::new(format!("Builtin swc-loader error: {}

Help:
The version of the SWC Wasm plugin you're using might not be compatible with `builtin:swc-loader`.

The `swc_core` version of the current `rspack_core` is {swc_core_version}. Please check the `swc_core` version of SWC Wasm plugin to make sure these versions are within the compatible range.
Versions of `swc_core` are more likely to be located in the `Cargo.toml` file in the root directory of these plugin repositories.

Check out this guide as a reference for selecting the versions of SWC Wasm plugins: https://swc.rs/docs/plugin/selecting-swc-core", $tt))
.boxed()
.into()
}}
}
if let Some(err) = err.downcast_ref::<String>() {
Err(swc_error!(err))
} else {
Err(swc_error!("unknown error"))
}
}
}
})
})
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = [
[
/The version of the SWC Wasm plugin you're using might not be compatible with \`builtin:swc-loader\`/
],
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

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

Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@


const rspack = require('@rspack/core');
const path = require('path');
const { RawSource } = require('webpack-sources');
/** @type {import('@rspack/cli').Configuration} */
const config = {
entry: {
main: './src/index.jsx',
},
resolve: {
extensions: ['...', '.jsx'],
alias: {
'@swc/helpers': path.dirname(require.resolve('@swc/helpers/package.json')),
},
},
module: {
rules: [
{
test: /\.(jsx|js)$/,
use: {
loader: 'builtin:swc-loader',
options: {
// Enable source map
sourceMap: true,
target: 'es5',
jsc: {
parser: {
syntax: 'ecmascript',
jsx: true,
},
externalHelpers: true,
preserveAllComments: false,
transform: {
react: {
runtime: 'automatic',
pragma: 'React.createElement',
pragmaFrag: 'React.Fragment',
throwIfNamespace: true,
useBuiltins: false,
},
},
experimental: {
cacheRoot: __dirname + "/.swc",
plugins: [
[
__dirname + "/node_modules/swc-wasm-plugin",
{
exclude: ["error"]
}
]
]
}
},
},
},
type: 'javascript/auto',
},
{
test: /\.(png|svg|jpg)$/,
type: 'asset/resource',
},
],
},
optimization: {
minimize: false, // Disabling minification because it takes too long on CI
},
plugins: [
new rspack.HtmlRspackPlugin({
template: './index.html',
}),
{
// Replace all assets with empty content to avoid evaluation that causes errors
apply(compiler) {
compiler.hooks.compilation.tap("_", (compilation) => {
compilation.hooks.processAssets.tap("_", (assets) => {
let names = Object.keys(assets);
names.forEach(name => {
assets[name] = new RawSource("")
})
})
})
}
}
],
experiments: { css: true }
};
module.exports = config;

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function App() {
return (
<div className="App">
<header className="App-header">
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}

export default App;
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { answer } from 'lib3';
console.log('answer:', answer());

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import("../../../..").TConfigCaseConfig} */
module.exports = {
noTests: true,
}
Loading