@rsbuild/webpack 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -43,7 +43,7 @@ async function createCompiler({
43
43
  const { default: webpack } = await Promise.resolve().then(() => __toESM(require("webpack")));
44
44
  const compiler = webpackConfigs.length === 1 ? webpack(webpackConfigs[0]) : webpack(webpackConfigs);
45
45
  let isFirstCompile = true;
46
- compiler.hooks.done.tap("done", async (stats) => {
46
+ compiler.hooks.done.tap("rsbuild:done", async (stats) => {
47
47
  const { message, level } = (0, import_shared.formatStats)(stats);
48
48
  if (level === "error") {
49
49
  import_shared.logger.error(message);
@@ -1,5 +1,3 @@
1
1
  import type { Compiler, MultiCompiler } from 'webpack';
2
- import type { ModernDevServerOptions } from '@modern-js/server';
3
- type DevMiddlewareOptions = ModernDevServerOptions['devMiddleware'];
4
- export declare const getDevMiddleware: (compiler: Compiler | MultiCompiler) => NonNullable<DevMiddlewareOptions>;
5
- export {};
2
+ import { DevMiddleware } from '@rsbuild/shared';
3
+ export declare const getDevMiddleware: (compiler: Compiler | MultiCompiler) => NonNullable<DevMiddleware>;
@@ -1,5 +1,4 @@
1
1
  import { StartDevServerOptions } from '@rsbuild/shared';
2
2
  import { InitConfigsOptions } from './initConfigs';
3
3
  import type { Compiler, MultiCompiler } from 'webpack';
4
- export declare function createDevServer(options: InitConfigsOptions, port: number, serverOptions: Exclude<StartDevServerOptions['serverOptions'], undefined>, customCompiler?: Compiler | MultiCompiler): Promise<import("@modern-js/server").Server>;
5
- export declare function startDevServer(options: InitConfigsOptions, startDevServerOptions?: StartDevServerOptions): Promise<import("@rsbuild/shared").StartServerResult>;
4
+ export declare function createDevServer(options: InitConfigsOptions, port: number, serverOptions: Exclude<StartDevServerOptions['serverOptions'], undefined>, customCompiler?: Compiler | MultiCompiler): Promise<import("@rsbuild/shared").ServerApi>;
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,27 +15,18 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
  var startDevServer_exports = {};
30
20
  __export(startDevServer_exports, {
31
- createDevServer: () => createDevServer,
32
- startDevServer: () => startDevServer
21
+ createDevServer: () => createDevServer
33
22
  });
34
23
  module.exports = __toCommonJS(startDevServer_exports);
35
24
  var import_shared = require("@rsbuild/shared");
36
25
  var import_createCompiler = require("./createCompiler");
37
26
  var import_initConfigs = require("./initConfigs");
38
27
  var import_devMiddleware = require("./devMiddleware");
28
+ var import_server = require("@rsbuild/core/server");
39
29
  async function createDevServer(options, port, serverOptions, customCompiler) {
40
- const { Server } = await Promise.resolve().then(() => __toESM(require("@modern-js/server")));
41
30
  let compiler;
42
31
  if (customCompiler) {
43
32
  compiler = customCompiler;
@@ -50,31 +39,21 @@ async function createDevServer(options, port, serverOptions, customCompiler) {
50
39
  }
51
40
  (0, import_shared.debug)("create dev server");
52
41
  const rsbuildConfig = options.context.config;
53
- const { config, devConfig } = await (0, import_shared.getDevServerOptions)({
42
+ const { devConfig } = await (0, import_shared.getDevServerOptions)({
54
43
  rsbuildConfig,
55
44
  serverOptions,
56
45
  port
57
46
  });
58
- const server = new Server({
47
+ const server = await (0, import_server.createDevServer)({
59
48
  pwd: options.context.rootPath,
60
49
  devMiddleware: (0, import_devMiddleware.getDevMiddleware)(compiler),
61
50
  ...serverOptions,
62
- dev: devConfig,
63
- config
51
+ dev: devConfig
64
52
  });
65
53
  (0, import_shared.debug)("create dev server done");
66
54
  return server;
67
55
  }
68
- async function startDevServer(options, startDevServerOptions = {}) {
69
- return (0, import_shared.startDevServer)(
70
- options,
71
- // @ts-expect-error compiler type mismatch
72
- createDevServer,
73
- startDevServerOptions
74
- );
75
- }
76
56
  // Annotate the CommonJS export names for ESM import in node:
77
57
  0 && (module.exports = {
78
- createDevServer,
79
- startDevServer
58
+ createDevServer
80
59
  });
@@ -128,11 +128,9 @@ const pluginBabel = () => ({
128
128
  excludes
129
129
  });
130
130
  rule.test(useTsLoader ? import_shared.JS_REGEX : (0, import_shared.mergeRegex)(import_shared.JS_REGEX, import_shared.TS_REGEX)).use(CHAIN_ID.USE.BABEL).loader(require.resolve("babel-loader")).options(babelOptions);
131
- if (config.source.compileJsDataURI) {
132
- chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).mimetype({
133
- or: ["text/javascript", "application/javascript"]
134
- }).use(CHAIN_ID.USE.BABEL).loader(require.resolve("babel-loader")).options(import_lodash.default.cloneDeep(babelOptions));
135
- }
131
+ chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).mimetype({
132
+ or: ["text/javascript", "application/javascript"]
133
+ }).use(CHAIN_ID.USE.BABEL).loader(require.resolve("babel-loader")).options(import_lodash.default.cloneDeep(babelOptions));
136
134
  (0, import_shared.addCoreJsEntry)({ chain, config, isServer, isServiceWorker });
137
135
  }
138
136
  );
@@ -37,10 +37,8 @@ const pluginBasic = () => ({
37
37
  name: "plugin-basic",
38
38
  setup(api) {
39
39
  (0, import_shared.applyBasicPlugin)(api);
40
- api.modifyWebpackChain(async (chain, { env, isServer, isWebWorker }) => {
41
- const maxAssetSize = isServer || isWebWorker ? 30 * 1e3 * 1e3 : 3 * 1e3 * 1e3;
42
- chain.performance.maxAssetSize(maxAssetSize);
43
- chain.performance.maxEntrypointSize(maxAssetSize);
40
+ api.modifyWebpackChain(async (chain, { env }) => {
41
+ chain.performance.hints(false);
44
42
  chain.module.parser.merge({
45
43
  javascript: {
46
44
  exportsPresence: "error"
@@ -50,7 +50,7 @@ async function applyBaseCSSRule({
50
50
  const enableSourceMap = (0, import_shared.isUseCssSourceMap)(config);
51
51
  const enableCSSModuleTS = Boolean(config.output.enableCssModuleTSDeclaration);
52
52
  const localIdentName = (0, import_shared.getCssModuleLocalIdentName)(config, isProd);
53
- const cssLoaderOptions = await (0, import_shared.getCssLoaderOptions)({
53
+ const cssLoaderOptions = (0, import_shared.getCssLoaderOptions)({
54
54
  config,
55
55
  enableSourceMap,
56
56
  importLoaders,
@@ -87,7 +87,7 @@ async function applyBaseCSSRule({
87
87
  }
88
88
  rule.use(CHAIN_ID.USE.CSS).loader(getCompiledPath("css-loader")).options(cssLoaderOptions).end();
89
89
  if (!isServer && !isWebWorker) {
90
- const postcssLoaderOptions = await (0, import_shared.getPostcssConfig)({
90
+ const postcssLoaderOptions = (0, import_shared.getPostcssConfig)({
91
91
  enableSourceMap,
92
92
  browserslist,
93
93
  config,
@@ -39,7 +39,7 @@ function pluginLess() {
39
39
  api.modifyBundlerChain(async (chain, utils) => {
40
40
  const config = api.getNormalizedConfig();
41
41
  const { applyBaseCSSRule } = await Promise.resolve().then(() => __toESM(require("./css")));
42
- const { options, excludes } = await (0, import_shared.getLessLoaderOptions)(
42
+ const { options, excludes } = (0, import_shared.getLessLoaderOptions)(
43
43
  config.tools.less,
44
44
  (0, import_shared.isUseCssSourceMap)(config)
45
45
  );
@@ -36,8 +36,9 @@ const pluginProgress = () => ({
36
36
  name: "plugin-progress",
37
37
  setup(api) {
38
38
  api.modifyWebpackChain(async (chain, { target, CHAIN_ID }) => {
39
+ var _a;
39
40
  const config = api.getNormalizedConfig();
40
- const options = config.dev.progressBar;
41
+ const options = (_a = config.dev.progressBar) != null ? _a : true;
41
42
  if (!options) {
42
43
  return;
43
44
  }
@@ -36,10 +36,10 @@ const pluginReactWebpack = () => ({
36
36
  name: "plugin-react-webpack",
37
37
  setup(api) {
38
38
  api.modifyRsbuildConfig(async (config, { mergeRsbuildConfig }) => {
39
+ const isNewJsx = await (0, import_shared.isBeyondReact17)(api.context.rootPath);
39
40
  const babelConfig = {
40
41
  tools: {
41
42
  babel(_, { addPresets, addPlugins }) {
42
- const isNewJsx = (0, import_shared.isBeyondReact17)(api.context.rootPath);
43
43
  const presetReactOptions = {
44
44
  development: !(0, import_shared.isProd)(),
45
45
  // Will use the native built-in instead of trying to polyfill
@@ -67,9 +67,7 @@ const pluginResolve = () => ({
67
67
  api.modifyWebpackChain(async (chain, { CHAIN_ID, target }) => {
68
68
  const config = api.getNormalizedConfig();
69
69
  const isTsProject = Boolean(api.context.tsconfigPath);
70
- if (config.source.compileJsDataURI) {
71
- chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).resolve.set("fullySpecified", false);
72
- }
70
+ chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).resolve.set("fullySpecified", false);
73
71
  if (isTsProject && config.source.aliasStrategy === "prefer-tsconfig") {
74
72
  await applyTsConfigPathsPlugin({
75
73
  chain,
@@ -35,14 +35,14 @@ var import_shared = require("@rsbuild/shared");
35
35
  function pluginSass() {
36
36
  return {
37
37
  name: "plugin-sass",
38
- async setup(api) {
38
+ setup(api) {
39
39
  api.onAfterCreateCompiler(({ compiler }) => {
40
40
  (0, import_shared.patchCompilerGlobalLocation)(compiler);
41
41
  });
42
42
  api.modifyBundlerChain(async (chain, utils) => {
43
43
  const config = api.getNormalizedConfig();
44
44
  const { applyBaseCSSRule } = await Promise.resolve().then(() => __toESM(require("./css")));
45
- const { options, excludes } = await (0, import_shared.getSassLoaderOptions)(
45
+ const { options, excludes } = (0, import_shared.getSassLoaderOptions)(
46
46
  config.tools.sass,
47
47
  // source-maps required for loaders preceding resolve-url-loader
48
48
  true
package/dist/provider.js CHANGED
@@ -32,6 +32,7 @@ __export(provider_exports, {
32
32
  });
33
33
  module.exports = __toCommonJS(provider_exports);
34
34
  var import_shared = require("@rsbuild/shared");
35
+ var import_server = require("@rsbuild/core/server");
35
36
  var import_createContext = require("./core/createContext");
36
37
  var import_plugin = require("./shared/plugin");
37
38
  var import_initConfigs = require("./core/initConfigs");
@@ -69,14 +70,16 @@ function webpackProvider({
69
70
  return createCompiler({ context, webpackConfigs });
70
71
  },
71
72
  async startDevServer(options) {
72
- const { startDevServer } = await Promise.resolve().then(() => __toESM(require("./core/startDevServer")));
73
- return startDevServer(
73
+ const { createDevServer } = await Promise.resolve().then(() => __toESM(require("./core/startDevServer")));
74
+ return (0, import_shared.startDevServer)(
74
75
  { context, pluginStore, rsbuildOptions },
76
+ // @ts-expect-error compiler type mismatch
77
+ createDevServer,
75
78
  options
76
79
  );
77
80
  },
78
81
  async preview() {
79
- return (0, import_shared.startProdServer)(context, context.config);
82
+ return (0, import_server.startProdServer)(context, context.config);
80
83
  },
81
84
  async build(options) {
82
85
  const { build: buildImpl, webpackBuild } = await Promise.resolve().then(() => __toESM(require("./core/build")));
@@ -78,7 +78,6 @@ const applyDefaultPlugins = (plugins) => {
78
78
  plugins.define(),
79
79
  Promise.resolve().then(() => __toESM(require("../plugins/progress"))).then((m) => m.pluginProgress()),
80
80
  Promise.resolve().then(() => __toESM(require("../plugins/minimize"))).then((m) => m.pluginMinimize()),
81
- Promise.resolve().then(() => __toESM(require("../plugins/moduleScopes"))).then((m) => m.pluginModuleScopes()),
82
81
  Promise.resolve().then(() => __toESM(require("../plugins/tsLoader"))).then((m) => m.pluginTsLoader()),
83
82
  Promise.resolve().then(() => __toESM(require("../plugins/babel"))).then((m) => m.pluginBabel()),
84
83
  Promise.resolve().then(() => __toESM(require("../plugins/css"))).then((m) => m.pluginCss()),
@@ -92,7 +91,6 @@ const applyDefaultPlugins = (plugins) => {
92
91
  Promise.resolve().then(() => __toESM(require("../plugins/sri"))).then((m) => m.pluginSRI()),
93
92
  (_c = plugins.startUrl) == null ? void 0 : _c.call(plugins),
94
93
  plugins.inlineChunk(),
95
- plugins.assetsRetry(),
96
94
  plugins.externals(),
97
95
  plugins.performance(),
98
96
  Promise.resolve().then(() => __toESM(require("../plugins/lazyCompilation"))).then((m) => m.pluginLazyCompilation()),
@@ -1,11 +1,9 @@
1
1
  import type { DeepReadonly } from '@rsbuild/shared';
2
2
  import type { NormalizedSecurityConfig, SecurityConfig } from './security';
3
- import type { NormalizedSourceConfig, SourceConfig } from './source';
4
3
  import type { NormalizedToolsConfig, ToolsConfig } from './tools';
5
- import type { DevConfig, HtmlConfig, OutputConfig, ExperimentsConfig, PerformanceConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedOutputConfig, NormalizedExperimentsConfig, NormalizedPerformanceConfig } from '@rsbuild/shared';
6
- export type { DevConfig, HtmlConfig, OutputConfig, ExperimentsConfig, PerformanceConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedOutputConfig, NormalizedExperimentsConfig, NormalizedPerformanceConfig };
4
+ import type { DevConfig, HtmlConfig, SourceConfig, OutputConfig, ExperimentsConfig, PerformanceConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedSourceConfig, NormalizedOutputConfig, NormalizedExperimentsConfig, NormalizedPerformanceConfig } from '@rsbuild/shared';
5
+ export type { DevConfig, HtmlConfig, SourceConfig, OutputConfig, ExperimentsConfig, PerformanceConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedSourceConfig, NormalizedOutputConfig, NormalizedExperimentsConfig, NormalizedPerformanceConfig };
7
6
  export * from './security';
8
- export * from './source';
9
7
  export * from './tools';
10
8
  /** The Rsbuild config when using Webpack as the bundler */
11
9
  export interface RsbuildConfig {
@@ -16,11 +16,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
16
16
  var config_exports = {};
17
17
  module.exports = __toCommonJS(config_exports);
18
18
  __reExport(config_exports, require("./security"), module.exports);
19
- __reExport(config_exports, require("./source"), module.exports);
20
19
  __reExport(config_exports, require("./tools"), module.exports);
21
20
  // Annotate the CommonJS export names for ESM import in node:
22
21
  0 && (module.exports = {
23
22
  ...require("./security"),
24
- ...require("./source"),
25
23
  ...require("./tools")
26
24
  });
@@ -87,7 +87,9 @@ class ProgressPlugin extends import_webpack.default.ProgressPlugin {
87
87
  compiler.hooks.done.tap(this.name, (stat) => {
88
88
  if (startTime) {
89
89
  this.hasCompileErrors = stat.hasErrors();
90
- this.compileTime = (0, import_shared.prettyTime)(process.hrtime(startTime));
90
+ const hrtime = process.hrtime(startTime);
91
+ const seconds = hrtime[0] + hrtime[1] / 1e9;
92
+ this.compileTime = (0, import_shared.prettyTime)(seconds);
91
93
  startTime = null;
92
94
  if (!this.hasCompileErrors) {
93
95
  import_shared.logger.ready(`${this.id} compiled in ${this.compileTime}`);
@@ -90,7 +90,7 @@ const renderBar = (option) => {
90
90
  const space = " ".repeat(spaceWidth);
91
91
  const percent = (0, import_utils.clamp)(Math.floor(current / total * 100), 0, 100);
92
92
  const barColor = import_shared.color[color];
93
- const backgroundColor = color[bgColor];
93
+ const backgroundColor = import_shared.color[bgColor];
94
94
  const doneColor = hasErrors ? import_shared.color.red : barColor;
95
95
  const idColor = done ? doneColor : barColor;
96
96
  const id = mergedOptions.id ? idColor(padding(mergedOptions.id, maxIdLen)) : "";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/webpack",
3
- "version": "0.0.16",
3
+ "version": "0.0.18",
4
4
  "homepage": "https://rsbuild.dev",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,7 +42,6 @@
42
42
  "dependencies": {
43
43
  "@babel/core": "^7.23.2",
44
44
  "@babel/preset-react": "^7.22.15",
45
- "@modern-js/server": "0.0.0-next-20231103131234",
46
45
  "@pmmmwh/react-refresh-webpack-plugin": "0.5.10",
47
46
  "babel-loader": "9.1.3",
48
47
  "babel-plugin-import": "1.13.5",
@@ -59,11 +58,11 @@
59
58
  "tsconfig-paths-webpack-plugin": "4.1.0",
60
59
  "webpack": "^5.89.0",
61
60
  "webpack-subresource-integrity": "5.1.0",
62
- "@rsbuild/babel-preset": "0.0.16",
63
- "@rsbuild/core": "0.0.16",
64
- "@rsbuild/plugin-babel": "0.0.16",
65
- "@rsbuild/plugin-css-minimizer": "0.0.16",
66
- "@rsbuild/shared": "0.0.16"
61
+ "@rsbuild/babel-preset": "0.0.18",
62
+ "@rsbuild/core": "0.0.18",
63
+ "@rsbuild/plugin-babel": "0.0.18",
64
+ "@rsbuild/plugin-css-minimizer": "0.0.18",
65
+ "@rsbuild/shared": "0.0.18"
67
66
  },
68
67
  "devDependencies": {
69
68
  "@types/lodash": "^4.14.200",
@@ -71,7 +70,7 @@
71
70
  "react": "^18.2.0",
72
71
  "react-dom": "^18.2.0",
73
72
  "typescript": "^5.2.2",
74
- "@rsbuild/test-helper": "0.0.16"
73
+ "@rsbuild/test-helper": "0.0.18"
75
74
  },
76
75
  "engines": {
77
76
  "node": ">=14.0.0"
@@ -1,5 +0,0 @@
1
- import { type ChainedConfig } from '@rsbuild/shared';
2
- import type { RsbuildPlugin, ModuleScopes } from '../types';
3
- export declare const isPrimitiveScope: (items: unknown[]) => items is (string | RegExp)[];
4
- export declare const applyScopeChain: (defaults: ModuleScopes, options: ChainedConfig<ModuleScopes>) => ModuleScopes;
5
- export declare const pluginModuleScopes: () => RsbuildPlugin;
@@ -1,85 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var moduleScopes_exports = {};
30
- __export(moduleScopes_exports, {
31
- applyScopeChain: () => applyScopeChain,
32
- isPrimitiveScope: () => isPrimitiveScope,
33
- pluginModuleScopes: () => pluginModuleScopes
34
- });
35
- module.exports = __toCommonJS(moduleScopes_exports);
36
- var import_path = __toESM(require("path"));
37
- var import_shared = require("@rsbuild/shared");
38
- const isPrimitiveScope = (items) => items.every(
39
- (item) => typeof item === "string" || Object.prototype.toString.call(item) === "[object RegExp]"
40
- );
41
- const applyScopeChain = (defaults, options) => {
42
- if (Array.isArray(options)) {
43
- if (isPrimitiveScope(options)) {
44
- return defaults.concat(options);
45
- }
46
- return options.reduce(applyScopeChain, defaults);
47
- }
48
- return options(defaults) || defaults;
49
- };
50
- const pluginModuleScopes = () => ({
51
- name: "plugin-module-scopes",
52
- setup(api) {
53
- api.modifyWebpackChain(async (chain, { CHAIN_ID }) => {
54
- const config = api.getNormalizedConfig();
55
- const scopeOptions = config.source.moduleScopes;
56
- if (!scopeOptions) {
57
- return;
58
- }
59
- const { ModuleScopePlugin } = await Promise.resolve().then(() => __toESM(require("../webpackPlugins/ModuleScopePlugin")));
60
- const scopes = applyScopeChain([], scopeOptions);
61
- const rootPackageJson = import_path.default.resolve(
62
- api.context.rootPath,
63
- "./package.json"
64
- );
65
- const formattedScopes = scopes.map((scope) => {
66
- if (typeof scope === "string") {
67
- return (0, import_shared.ensureAbsolutePath)(api.context.rootPath, scope);
68
- }
69
- return scope;
70
- });
71
- chain.resolve.plugin(CHAIN_ID.RESOLVE_PLUGIN.MODULE_SCOPE).use(ModuleScopePlugin, [
72
- {
73
- scopes: formattedScopes,
74
- allowedFiles: [rootPackageJson]
75
- }
76
- ]);
77
- });
78
- }
79
- });
80
- // Annotate the CommonJS export names for ESM import in node:
81
- 0 && (module.exports = {
82
- applyScopeChain,
83
- isPrimitiveScope,
84
- pluginModuleScopes
85
- });
@@ -1,26 +0,0 @@
1
- import type { ChainedConfig, SourceConfig as BaseSourceConfig, NormalizedSourceConfig as BaseNormalizedSourceConfig } from '@rsbuild/shared';
2
- export type ModuleScopes = Array<string | RegExp>;
3
- export type TransformImport = {
4
- libraryName: string;
5
- libraryDirectory?: string;
6
- style?: string | boolean;
7
- styleLibraryDirectory?: string;
8
- camelToDashComponentName?: boolean;
9
- transformToDefaultImport?: boolean;
10
- customName?: ((member: string) => string | undefined) | string;
11
- customStyleName?: ((member: string) => string | undefined) | string;
12
- };
13
- export interface SourceConfig extends BaseSourceConfig {
14
- /**
15
- * Restrict importing paths. After configuring this option, all source files can only import code from
16
- * the specific paths, and import code from other paths is not allowed.
17
- */
18
- moduleScopes?: ChainedConfig<ModuleScopes>;
19
- }
20
- export interface NormalizedSourceConfig extends BaseNormalizedSourceConfig {
21
- /**
22
- * Restrict importing paths. After configuring this option, all source files can only import code from
23
- * the specific paths, and import code from other paths is not allowed.
24
- */
25
- moduleScopes?: ChainedConfig<ModuleScopes>;
26
- }
@@ -1,16 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __copyProps = (to, from, except, desc) => {
7
- if (from && typeof from === "object" || typeof from === "function") {
8
- for (let key of __getOwnPropNames(from))
9
- if (!__hasOwnProp.call(to, key) && key !== except)
10
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- }
12
- return to;
13
- };
14
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
- var source_exports = {};
16
- module.exports = __toCommonJS(source_exports);
@@ -1,16 +0,0 @@
1
- export declare class ModuleScopePlugin {
2
- scopes: Array<string | RegExp>;
3
- allowedFiles: Set<string>;
4
- allowedDirs: string[];
5
- allowedPatterns: RegExp[];
6
- relativeAllowedDirs: string[];
7
- cache: Map<string, boolean>;
8
- constructor({
9
- scopes,
10
- allowedFiles
11
- }: {
12
- scopes: Array<string | RegExp>;
13
- allowedFiles?: string[];
14
- });
15
- apply(resolver: any): void;
16
- }
@@ -1,110 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var ModuleScopePlugin_exports = {};
20
- __export(ModuleScopePlugin_exports, {
21
- ModuleScopePlugin: () => ModuleScopePlugin
22
- });
23
- module.exports = __toCommonJS(ModuleScopePlugin_exports);
24
- var import_path = require("path");
25
- var import_shared = require("@rsbuild/shared");
26
- class ModuleScopePlugin {
27
- constructor({
28
- scopes,
29
- allowedFiles = []
30
- }) {
31
- this.scopes = scopes;
32
- this.allowedFiles = new Set(allowedFiles);
33
- this.allowedDirs = scopes.filter(import_shared.isString);
34
- this.allowedPatterns = scopes.filter(import_shared.isRegExp);
35
- this.relativeAllowedDirs = this.allowedDirs.map(
36
- (allowedDir) => `${(0, import_path.relative)((0, import_path.dirname)(allowedDir), allowedDir)}/`
37
- );
38
- this.cache = /* @__PURE__ */ new Map();
39
- }
40
- apply(resolver) {
41
- const { allowedFiles, allowedDirs, allowedPatterns, relativeAllowedDirs } = this;
42
- resolver.hooks.file.tapAsync(
43
- "ModuleScopePlugin",
44
- (request, contextResolver, callback) => {
45
- const { issuer } = request.context;
46
- if (!issuer || this.cache.get(issuer)) {
47
- return callback();
48
- }
49
- this.cache.set(issuer, true);
50
- if (
51
- // If this resolves to a node_module, we don't care what happens next
52
- request.descriptionFileRoot.indexOf("/node_modules/") !== -1 || request.descriptionFileRoot.indexOf("\\node_modules\\") !== -1 || !request.__innerRequest_request
53
- ) {
54
- return callback();
55
- }
56
- if (allowedDirs.every((allowedDir) => {
57
- const result = (0, import_path.relative)(allowedDir, issuer);
58
- return result.startsWith("../") || result.startsWith("..\\");
59
- })) {
60
- return callback();
61
- }
62
- const requestFullPath = (0, import_path.resolve)(
63
- (0, import_path.dirname)(issuer),
64
- request.__innerRequest_request
65
- );
66
- if (allowedPatterns.some(
67
- (allowedPattern) => allowedPattern.test(requestFullPath)
68
- )) {
69
- return callback();
70
- }
71
- if (allowedFiles.has(requestFullPath)) {
72
- return callback();
73
- }
74
- if (allowedDirs.every((allowedDir) => {
75
- const requestRelative = (0, import_path.relative)(allowedDir, requestFullPath);
76
- return requestRelative.startsWith("../") || requestRelative.startsWith("..\\");
77
- })) {
78
- let message = `You attempted to import ${import_shared.color.bold(
79
- request.__innerRequest_request
80
- )} which is not allowed. `;
81
- if (allowedDirs.length) {
82
- message += `Allowed dirs: ${import_shared.color.bold(
83
- relativeAllowedDirs.join(",")
84
- )}. `;
85
- }
86
- if (allowedPatterns.length) {
87
- message += `Allowed patterns: ${import_shared.color.bold(
88
- allowedPatterns.map((p) => p.toString()).join(",")
89
- )}. `;
90
- }
91
- message += `Please check the source.moduleScopes configuration.`;
92
- const scopeError = new Error(message);
93
- Object.defineProperty(scopeError, "ModuleScopePlugin", {
94
- value: true,
95
- writable: false,
96
- enumerable: false
97
- });
98
- this.cache.set(issuer, false);
99
- return callback(scopeError, request);
100
- } else {
101
- return callback();
102
- }
103
- }
104
- );
105
- }
106
- }
107
- // Annotate the CommonJS export names for ESM import in node:
108
- 0 && (module.exports = {
109
- ModuleScopePlugin
110
- });