Skip to content
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
55 changes: 48 additions & 7 deletions crates/rspack_plugin_esm_library/src/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,23 @@ use rspack_core::{
reserved_names::RESERVED_NAMES, rspack_sources::ReplaceSource, split_readable_identifier,
to_normal_comment,
};
use rspack_error::{Diagnostic, Result};
use rspack_error::{Diagnostic, Error, Result};
use rspack_javascript_compiler::ast::Ast;
use rspack_plugin_javascript::{
JsPlugin, RenderSource, dependency::ESMExportImportedSpecifierDependency,
visitors::swc_visitor::resolver,
};
use rspack_util::{
SpanExt,
atom::Atom,
fx_hash::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, indexmap},
swc::join_atom,
};
use swc_core::{
common::{FileName, SyntaxContext},
common::{FileName, Spanned, SyntaxContext},
ecma::{
ast::{EsVersion, Program},
parser::{Syntax, parse_file_as_module},
parser::{EsSyntax, Syntax, parse_file_as_module},
},
};

Expand Down Expand Up @@ -166,6 +167,15 @@ impl EsmLibraryPlugin {
let mut hoisted_modules = IdentifierIndexSet::default();

for m in modules.iter() {
if compilation
.code_generation_results
.get_one(m)
.get(&SourceType::JavaScript)
.is_none()
{
continue;
}

let info = concate_modules_map
.get(m)
.unwrap_or_else(|| panic!("should have set module info for {m}"));
Expand Down Expand Up @@ -761,6 +771,16 @@ var {} = {{}};
let m = module_graph
.module_by_identifier(&id)
.expect("should have module");
let jsx = m
.as_ref()
.as_normal_module()
.and_then(|normal_module| normal_module.get_parser_options())
.and_then(|options| {
options
.get_javascript()
.and_then(|js_options| js_options.jsx)
})
.unwrap_or(false);
let cm: Arc<swc_core::common::SourceMap> = Default::default();
let readable_identifier = m.readable_identifier(&compilation.options.context);
let fm = cm.new_source_file(
Expand All @@ -772,14 +792,28 @@ var {} = {{}};
.into_owned(),
);
let mut errors = vec![];
let module = parse_file_as_module(
let module = match parse_file_as_module(
&fm,
Syntax::default(),
Syntax::Es(EsSyntax {
jsx,
..Default::default()
}),
EsVersion::EsNext,
None,
&mut errors,
)
.expect("parse failed");
) {
Ok(module) => module,
Err(err) => {
// return empty error as we already push error to compilation.diagnostics
return Err(Error::from_string(
Some(fm.src.clone().into_string()),
err.span().real_lo() as usize,
err.span().real_hi() as usize,
"JavaScript parse error:\n".to_string(),
err.kind().msg().to_string(),
));
}
};
let mut ast = Ast::new(Program::Module(module), cm, None);

let mut global_ctxt = SyntaxContext::empty();
Expand Down Expand Up @@ -1330,6 +1364,13 @@ var {} = {{}};
.all_dependencies()
.chain(compilation.global_entry.all_dependencies())
.filter_map(|dep_id| module_graph.module_identifier_by_dependency_id(dep_id))
.filter(|module| {
compilation
.code_generation_results
.get_one(module)
.get(&SourceType::JavaScript)
.is_some()
})
.copied()
{
let entry_module_chunk = Self::get_module_chunk(entry_module, compilation);
Expand Down
27 changes: 15 additions & 12 deletions crates/rspack_plugin_esm_library/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,7 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> {
self_path.pop();

let chunk_ids_to_ukey = self.chunk_ids_to_ukey.borrow();

for captures in RSPACK_ESM_CHUNK_PLACEHOLDER_RE.find_iter(&content) {
let chunk_id = captures
.as_str()
Expand All @@ -440,25 +441,27 @@ async fn process_assets(&self, compilation: &mut Compilation) -> Result<()> {
let js_files = chunk
.files()
.iter()
.filter(|f| f.ends_with("js"))
.filter(|f| {
// find ref asset info
let Some(asset) = compilation.assets().get(*f) else {
return false;
};
asset.get_info().javascript_module.unwrap_or_default()
})
.collect::<Vec<_>>();
if js_files.len() > 1 {
return Err(rspack_error::error!(
"chunk has more than one file: {:?}, which is not supported in esm library",
js_files
));
}
let chunk_path = output_path.join(
js_files
.first()
.unwrap_or_else(|| {
panic!(
"at least one path for chunk: {:?}",
chunk.id().map(|id| { id.as_str() })
)
})
.as_str(),
);
if js_files.is_empty() {
return Err(rspack_error::error!(
"chunk {:?} should have at least one file",
chunk.id()
));
}
let chunk_path = output_path.join(js_files.first().expect("should have at least one file"));
let relative = chunk_path.relative(self_path.as_path());
let relative = relative
.to_slash()
Expand Down
8 changes: 7 additions & 1 deletion crates/rspack_plugin_esm_library/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ var {} = {{}};
}

let mut already_required = IdentifierIndexSet::default();

for m in &chunk_link.hoisted_modules {
let info = concatenated_modules_map
.get(m)
Expand Down Expand Up @@ -729,7 +730,12 @@ var {} = {{}};
info: &ConcatenatedModuleInfo,
chunk_link: &ChunkLinkContext,
) -> Result<ReplaceSource> {
let mut source = info.source.clone().expect("should have source");
let Some(mut source) = info.source.clone() else {
return Err(rspack_error::Error::error(format!(
"module: {} has no source",
info.module
)));
};

for ((atom, ctxt), refs) in &info.binding_to_ref {
if ctxt == &info.global_ctxt
Expand Down
20 changes: 18 additions & 2 deletions packages/rspack-test-tools/src/case/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ export function defaultOptions(
};
}

export function enableEsmLibraryPlugin(options: RspackOptions): boolean {
return (
options.output?.library === 'modern-module' ||
(typeof options.output?.library === 'object' &&
(options.output?.library as { type: string }).type === 'modern-module')
);
}

export function overrideOptions(
index: number,
context: ITestContext,
Expand All @@ -113,9 +121,17 @@ export function overrideOptions(
options.amd = {};
}
if (!options.output?.filename) {
const outputModule = options.experiments?.outputModule;
const runtimeChunkForModernModule =
options.optimization?.runtimeChunk === undefined &&
enableEsmLibraryPlugin(options);
const outputModule =
options.experiments?.outputModule || enableEsmLibraryPlugin(options);
options.output ??= {};
options.output.filename = `bundle${index}${outputModule ? '.mjs' : '.js'}`;
options.output.filename = `${runtimeChunkForModernModule ? `[name]${outputModule ? '.mjs' : '.js'}` : `bundle${index}${outputModule ? '.mjs' : '.js'}`}`;
}
if (enableEsmLibraryPlugin(options)) {
options.optimization ??= {};
options.optimization.runtimeChunk ??= { name: `runtime~${index}` };
}

if (options.cache === undefined) options.cache = false;
Expand Down
7 changes: 5 additions & 2 deletions packages/rspack-test-tools/src/runner/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import vm, { SourceTextModule } from 'node:vm';
import type { RspackOptions, StatsCompilation } from '@rspack/core';
import { enableEsmLibraryPlugin } from '../../case/config';
import asModule from '../../helper/legacy/asModule';
import createFakeWorker from '../../helper/legacy/createFakeWorker';
import urlToRelativePath from '../../helper/legacy/urlToRelativePath';
Expand Down Expand Up @@ -306,15 +307,17 @@ export class NodeRunner implements ITestRunner {
file,
});
}

if (
file.path.endsWith('.mjs') &&
this._options.compilerOptions.experiments?.outputModule
file.path.endsWith('.mjs') ||
enableEsmLibraryPlugin(this._options.compilerOptions)
) {
return this.requirers.get('esm')!(currentDirectory, modulePath, {
...context,
file,
});
}

return this.requirers.get('cjs')!(currentDirectory, modulePath, {
...context,
file,
Expand Down
1 change: 1 addition & 0 deletions packages/rspack/etc/core.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -4428,6 +4428,7 @@ export type LibraryOptions = {
name?: LibraryName;
type: LibraryType;
umdNamedDefine?: UmdNamedDefine;
preserveModules?: string;
};

// @public
Expand Down
16 changes: 3 additions & 13 deletions packages/rspack/src/builtin-plugin/EsmLibraryPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import { BuiltinPluginName } from '@rspack/binding';
import type { Compiler } from '../Compiler';
import type { RspackOptionsNormalized } from '../config';
import WebpackError from '../lib/WebpackError';
import type { Logger } from '../logging/Logger';
import { RemoveDuplicateModulesPlugin } from './RemoveDuplicateModulesPlugin';

function applyLimits(options: RspackOptionsNormalized, logger: Logger) {
export function applyLimits(options: RspackOptionsNormalized) {
// concatenateModules is not supported in ESM library mode, it has its own scope hoist algorithm
options.optimization.concatenateModules = false;

Expand All @@ -19,20 +18,13 @@ function applyLimits(options: RspackOptionsNormalized, logger: Logger) {
options.output.module = true;

if (options.output.chunkLoading && options.output.chunkLoading !== 'import') {
logger.warn(
`\`output.chunkLoading\` should be \`"import"\` or \`false\`, but got ${options.output.chunkLoading}, changed it to \`"import"\``,
);
options.output.chunkLoading = 'import';
}

if (options.output.chunkLoading === undefined) {
options.output.chunkLoading = 'import';
}

if (options.output.library) {
options.output.library = undefined;
}

let { splitChunks } = options.optimization;
if (splitChunks === undefined) {
splitChunks = options.optimization.splitChunks = {};
Expand All @@ -58,10 +50,7 @@ export class EsmLibraryPlugin {
}

apply(compiler: Compiler) {
const logger = compiler.getInfrastructureLogger(
EsmLibraryPlugin.PLUGIN_NAME,
);
applyLimits(compiler.options, logger);
applyLimits(compiler.options);
new RemoveDuplicateModulesPlugin().apply(compiler);

let err;
Expand All @@ -86,6 +75,7 @@ function checkConfig(config: RspackOptionsNormalized): string | undefined {
}

if (config.output.chunkFormat !== false) {
console.log(config.output.chunkFormat);
return 'You should disable default chunkFormat by `config.output.chunkFormat = false`';
}
}
10 changes: 7 additions & 3 deletions packages/rspack/src/config/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import fs from 'node:fs';
import path from 'node:path';
import {
applyLimits,
LightningCssMinimizerRspackPlugin,
SwcJsMinimizerRspackPlugin,
} from '../builtin-plugin';
Expand All @@ -22,7 +23,6 @@ import type {
EntryDescriptionNormalized,
EntryNormalized,
ExperimentsNormalized,
OutputNormalized,
RspackOptionsNormalized,
} from './normalization';
import {
Expand Down Expand Up @@ -110,7 +110,7 @@ export const applyRspackOptionsDefaults = (
deferImport: options.experiments.deferImport,
});

applyOutputDefaults(options.output, {
applyOutputDefaults(options, {
context: options.context!,
targetProperties,
isAffectedByBrowserslist:
Expand Down Expand Up @@ -505,7 +505,7 @@ const applyModuleDefaults = (
};

const applyOutputDefaults = (
output: OutputNormalized,
options: RspackOptionsNormalized,
{
context,
outputModule,
Expand All @@ -520,6 +520,7 @@ const applyOutputDefaults = (
entry: EntryNormalized;
},
) => {
const { output } = options;
const getLibraryName = (library: Library): string => {
const libraryName =
typeof library === 'object' && library && !Array.isArray(library)
Expand Down Expand Up @@ -835,6 +836,9 @@ const applyOutputDefaults = (
enabledLibraryTypes.push(desc.library.type);
}
});
if (enabledLibraryTypes.includes('modern-module')) {
applyLimits(options);
}
return enabledLibraryTypes;
});
A(output, 'enabledChunkLoadingTypes', () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/rspack/src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,11 @@ export type LibraryOptions = {
* Otherwise, an anonymous define is used.
* */
umdNamedDefine?: UmdNamedDefine;

/**
* PreserveModules only works for `modern-module`
*/
preserveModules?: string;
};

/** Options for library. */
Expand Down
Loading
Loading