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

feat: support checkResource option in IgnorePlugin #6249

Merged
merged 6 commits into from
Apr 16, 2024
Merged
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
2 changes: 2 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -896,8 +896,9 @@ export interface RawHttpExternalsRspackPluginOptions {
}

export interface RawIgnorePluginOptions {
resourceRegExp: RegExp
resourceRegExp?: RegExp
contextRegExp?: RegExp
checkResource?: (resource: string, context: string) => boolean
}

export interface RawInfo {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,42 @@
use derivative::Derivative;
use napi_derive::napi;
use rspack_napi::regexp::{JsRegExp, JsRegExpExt};
use rspack_plugin_ignore::IgnorePluginOptions;
use rspack_napi::{
regexp::{JsRegExp, JsRegExpExt},
threadsafe_function::ThreadsafeFunction,
};
use rspack_plugin_ignore::{CheckResourceContent, IgnorePluginOptions};

type RawCheckResource = ThreadsafeFunction<(String, String), bool>;

#[derive(Derivative)]
#[derivative(Debug)]
#[napi(object, object_to_js = false)]
pub struct RawIgnorePluginOptions {
#[napi(ts_type = "RegExp")]
pub resource_reg_exp: JsRegExp,
pub resource_reg_exp: Option<JsRegExp>,
#[napi(ts_type = "RegExp")]
pub context_reg_exp: Option<JsRegExp>,
#[napi(ts_type = "(resource: string, context: string) => boolean")]
pub check_resource: Option<RawCheckResource>,
}

impl From<RawIgnorePluginOptions> for IgnorePluginOptions {
fn from(value: RawIgnorePluginOptions) -> Self {
Self {
resource_reg_exp: value.resource_reg_exp.to_rspack_regex(),
resource_reg_exp: value
.resource_reg_exp
.map(|resource_reg_exp| resource_reg_exp.to_rspack_regex()),
context_reg_exp: value
.context_reg_exp
.map(|context_reg_exp| context_reg_exp.to_rspack_regex()),

check_resource: value.check_resource.map(|check_resource| {
CheckResourceContent::Fn(Box::new(move |resource, context| {
let f = check_resource.clone();

Box::pin(async move { f.call((resource.to_owned(), context.to_owned())).await })
}))
}),
}
}
}
2 changes: 2 additions & 0 deletions crates/rspack_plugin_ignore/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
derivative = { workspace = true }
futures = { workspace = true }
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_hook = { path = "../rspack_hook" }
Expand Down
50 changes: 39 additions & 11 deletions crates/rspack_plugin_ignore/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::fmt::Debug;

use derivative::Derivative;
use futures::future::BoxFuture;
use rspack_core::{
ApplyContext, CompilerOptions, ContextModuleFactoryBeforeResolve, ModuleFactoryCreateData,
NormalModuleFactoryBeforeResolve, Plugin, PluginContext,
Expand All @@ -8,10 +10,20 @@ use rspack_error::Result;
use rspack_hook::{plugin, plugin_hook};
use rspack_regex::RspackRegex;

#[derive(Debug)]
pub type CheckResourceFn =
Box<dyn for<'a> Fn(&'a str, &'a str) -> BoxFuture<'a, Result<bool>> + Sync + Send>;

pub enum CheckResourceContent {
Fn(CheckResourceFn),
}

#[derive(Derivative)]
#[derivative(Debug)]
pub struct IgnorePluginOptions {
pub resource_reg_exp: RspackRegex,
pub resource_reg_exp: Option<RspackRegex>,
pub context_reg_exp: Option<RspackRegex>,
#[derivative(Debug = "ignore")]
pub check_resource: Option<CheckResourceContent>,
}

#[plugin]
Expand All @@ -25,30 +37,46 @@ impl IgnorePlugin {
Self::new_inner(options)
}

fn check_ignore(&self, data: &mut ModuleFactoryCreateData) -> Option<bool> {
let resource_reg_exp: &RspackRegex = &self.options.resource_reg_exp;
async fn check_ignore(&self, data: &mut ModuleFactoryCreateData) -> Option<bool> {
if let Some(check_resource) = &self.options.check_resource {
if let Some(request) = data.request() {
match check_resource {
CheckResourceContent::Fn(check) => {
if check(request, data.context.as_ref())
.await
.expect("run IgnorePlugin check resource error")
{
return Some(false);
}
}
}
}
}

if resource_reg_exp.test(data.request()?) {
if let Some(context_reg_exp) = &self.options.context_reg_exp {
if context_reg_exp.test(&data.context) {
if let Some(resource_reg_exp) = &self.options.resource_reg_exp {
if resource_reg_exp.test(data.request()?) {
if let Some(context_reg_exp) = &self.options.context_reg_exp {
if context_reg_exp.test(&data.context) {
return Some(false);
}
} else {
return Some(false);
}
} else {
return Some(false);
}
}

None
}
}

#[plugin_hook(NormalModuleFactoryBeforeResolve for IgnorePlugin)]
async fn nmf_before_resolve(&self, data: &mut ModuleFactoryCreateData) -> Result<Option<bool>> {
Ok(self.check_ignore(data))
Ok(self.check_ignore(data).await)
}

#[plugin_hook(ContextModuleFactoryBeforeResolve for IgnorePlugin)]
async fn cmf_before_resolve(&self, data: &mut ModuleFactoryCreateData) -> Result<Option<bool>> {
Ok(self.check_ignore(data))
Ok(self.check_ignore(data).await)
}

impl Plugin for IgnorePlugin {
Expand Down
9 changes: 7 additions & 2 deletions packages/rspack/etc/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1274,7 +1274,7 @@ export type HtmlRspackPluginOptions = z.infer<typeof htmlRspackPluginOptions>;

// @public (undocumented)
export const IgnorePlugin: {
new (options: RawIgnorePluginOptions): {
new (options: IgnorePluginOptions): {
name: BuiltinPluginName;
_options: RawIgnorePluginOptions;
affectedHooks: "done" | "compilation" | "make" | "compile" | "emit" | "afterEmit" | "invalid" | "thisCompilation" | "afterDone" | "normalModuleFactory" | "contextModuleFactory" | "initialize" | "shouldEmit" | "infrastructureLog" | "beforeRun" | "run" | "assetEmitted" | "failed" | "shutdown" | "watchRun" | "watchClose" | "environment" | "afterEnvironment" | "afterPlugins" | "afterResolvers" | "beforeCompile" | "afterCompile" | "finishMake" | "entryOption" | undefined;
Expand All @@ -1284,7 +1284,12 @@ export const IgnorePlugin: {
};

// @public (undocumented)
export type IgnorePluginOptions = RawIgnorePluginOptions;
export type IgnorePluginOptions = {
resourceRegExp: NonNullable<RawIgnorePluginOptions["resourceRegExp"]>;
contextRegExp?: RawIgnorePluginOptions["contextRegExp"];
} | {
checkResource: NonNullable<RawIgnorePluginOptions["checkResource"]>;
};

// Warning: (ae-forgotten-export) The symbol "ignoreWarnings" needs to be exported by the entry point index.d.ts
//
Expand Down
27 changes: 25 additions & 2 deletions packages/rspack/src/builtin-plugin/IgnorePlugin.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,32 @@
import { BuiltinPluginName, RawIgnorePluginOptions } from "@rspack/binding";
import { z } from "zod";
import { validate } from "../util/validate";
import { create } from "./base";

export type IgnorePluginOptions = RawIgnorePluginOptions;
export type IgnorePluginOptions =
| {
resourceRegExp: NonNullable<RawIgnorePluginOptions["resourceRegExp"]>;
contextRegExp?: RawIgnorePluginOptions["contextRegExp"];
}
| {
checkResource: NonNullable<RawIgnorePluginOptions["checkResource"]>;
};

const IgnorePluginOptions = z.union([
z.object({
contextRegExp: z.instanceof(RegExp).optional(),
resourceRegExp: z.instanceof(RegExp)
}),
z.object({
checkResource: z.function(z.tuple([z.string(), z.string()]), z.boolean())
})
]);

export const IgnorePlugin = create(
BuiltinPluginName.IgnorePlugin,
(options: IgnorePluginOptions): RawIgnorePluginOptions => options
(options: IgnorePluginOptions): RawIgnorePluginOptions => {
validate(options, IgnorePluginOptions);

return options;
}
);

This file was deleted.

This file was deleted.

This file was deleted.

16 changes: 10 additions & 6 deletions website/docs/en/plugins/webpack/ignore-plugin.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ new rspack.IgnorePlugin(options);
- **Type:**

```ts
{
/** A RegExp to test the resource against. */
resourceRegExp: RegExp;
/** A RegExp to test the context (directory) against. */
contextRegExp?: RegExp;
}
| {
/** A RegExp to test the resource against. */
resourceRegExp: RegExp;
/** A RegExp to test the context (directory) against. */
contextRegExp?: RegExp;
}
| {
/** A Filter function that receives `resource` and `context` as arguments, must return boolean. */
checkResource: (resource: string, context: string) => boolean;
}
```

- **Default:** `undefined`
Expand Down
16 changes: 10 additions & 6 deletions website/docs/zh/plugins/webpack/ignore-plugin.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ new rspack.IgnorePlugin(options);
- **类型:**

```ts
{
/** 用于匹配资源文件 */
resourceRegExp: RegExp;
/** 用于匹配请求的目录 */
contextRegExp?: RegExp;
}
| {
/** 用于匹配资源文件 */
resourceRegExp: RegExp;
/** 用于匹配请求的目录 */
contextRegExp?: RegExp;
}
| {
/** 根据资源和请求的目录进行过滤 */
checkResource: (resource: string, context: string) => boolean;
}
```

- **默认值:** `undefined`
Expand Down
Loading