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

chore: commonjs exports dependency #4720

Merged
merged 2 commits into from
Nov 22, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ source: crates/rspack_testing/src/run_fixture.rs
(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], {
"./zh_locale.js": (function (__unused_webpack_module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
Object.defineProperty(exports, "__esModule", ({
value: true
});
}));
exports["default"] = void 0;
/* eslint-disable no-template-curly-in-string */ var _default = {};
exports["default"] = _default;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ source: crates/rspack_testing/src/run_fixture.rs
(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], {
"./zh_locale.js": (function (__unused_webpack_module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
Object.defineProperty(exports, "__esModule", ({
value: true
});
}));
exports["default"] = void 0;
/* eslint-disable no-template-curly-in-string */ var _default = {};
exports["default"] = _default;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ __webpack_require__.r(__webpack_exports__);
/*#__PURE__*/ (_lib__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (_lib__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(_lib__WEBPACK_IMPORTED_MODULE_0__, 2)));
}),
"./lib.js": (function (__unused_webpack_module, exports, __webpack_require__) {
exports['a'] = 100000;
exports.a = 100000;
}),

},function(__webpack_require__) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ __webpack_require__.r(__webpack_exports__);
/*#__PURE__*/ (_lib__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (_lib__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(_lib__WEBPACK_IMPORTED_MODULE_0__, 2)));
}),
"./lib.js": (function (__unused_webpack_module, exports, __webpack_require__) {
exports['a'] = 100000;
exports.a = 100000;
}),

},function(__webpack_require__) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ __webpack_require__.el(/* ./bar */"./bar.js").then(__webpack_require__.bind(__we
console.log(mod);
});
const a = "a";
exports.test = 30;
__webpack_exports__.test = 30;
}),
"./foo.js": (function (module, exports, __webpack_require__) {
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ __webpack_require__.el(/* ./bar */"./bar.js").then(__webpack_require__.bind(__we
console.log(mod);
});
const a = "a";
exports.test = 30;
__webpack_exports__.test = 30;
}),
"./foo.js": (function (module, exports, __webpack_require__) {
{
Expand Down
3 changes: 3 additions & 0 deletions crates/rspack_core/src/dependency/dependency_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pub enum DependencyType {
DynamicImportEager,
// cjs require
CjsRequire,
// cjs exports
CjsExports,
// new URL("./foo", import.meta.url)
NewUrl,
// new Worker()
Expand Down Expand Up @@ -75,6 +77,7 @@ impl DependencyType {
DependencyType::EsmImportSpecifier => Cow::Borrowed("esm import specifier"),
DependencyType::DynamicImport => Cow::Borrowed("dynamic import"),
DependencyType::CjsRequire => Cow::Borrowed("cjs require"),
DependencyType::CjsExports => Cow::Borrowed("cjs exports"),
DependencyType::NewUrl => Cow::Borrowed("new URL()"),
DependencyType::NewWorker => Cow::Borrowed("new Worker()"),
DependencyType::ImportMetaHotAccept => Cow::Borrowed("import.meta.webpackHot.accept"),
Expand Down
2 changes: 1 addition & 1 deletion crates/rspack_core/src/dependency/runtime_template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub fn export_from_import(
format!("var {import_var}_namespace_cache;\n",),
InitFragmentStage::StageHarmonyExports,
-1,
InitFragmentKey::uniqie(),
InitFragmentKey::unique(),
None,
)
.boxed(),
Expand Down
7 changes: 5 additions & 2 deletions crates/rspack_core/src/exports_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,10 @@ impl ExportsInfoId {
let info = self.get_read_only_export_info(&name, mg);
info.get_used_name(&name, runtime).map(UsedName::Str)
}
UsedName::Vec(_) => todo!(),
UsedName::Vec(_) => {
// TODO
Some(name.clone())
}
}
}

Expand Down Expand Up @@ -514,7 +517,7 @@ impl ExportsInfo {
}
}

#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum UsedName {
Str(JsWord),
Vec(Vec<JsWord>),
Expand Down
12 changes: 6 additions & 6 deletions crates/rspack_core/src/init_fragment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ pub struct InitFragmentContents {
pub end: Option<String>,
}

pub struct InitFragmentKeyUniqie;
pub type InitFragmentKeyUKey = rspack_database::Ukey<InitFragmentKeyUniqie>;
pub struct InitFragmentKeyUnique;
pub type InitFragmentKeyUKey = rspack_database::Ukey<InitFragmentKeyUnique>;

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum InitFragmentKey {
Expand All @@ -31,12 +31,12 @@ pub enum InitFragmentKey {
AwaitDependencies,
HarmonyCompatibility,
ModuleDecorator(String /* module_id */),
Uniqie(InitFragmentKeyUKey),
Unique(InitFragmentKeyUKey),
}

impl InitFragmentKey {
pub fn uniqie() -> Self {
Self::Uniqie(rspack_database::Ukey::new())
pub fn unique() -> Self {
Self::Unique(rspack_database::Ukey::new())
}
}

Expand Down Expand Up @@ -79,7 +79,7 @@ impl InitFragmentKey {
| InitFragmentKey::HarmonyExportStar(_)
| InitFragmentKey::ExternalModule(_)
| InitFragmentKey::ModuleDecorator(_) => first(fragments),
InitFragmentKey::HarmonyCompatibility | InitFragmentKey::Uniqie(_) => {
InitFragmentKey::HarmonyCompatibility | InitFragmentKey::Unique(_) => {
debug_assert!(fragments.len() == 1, "fragment = {:?}", self);
first(fragments)
}
Expand Down
3 changes: 3 additions & 0 deletions crates/rspack_core/src/runtime_globals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ bitflags! {
* the System.register context object
*/
const SYSTEM_CONTEXT = 1 << 49;

const THIS_AS_EXPORTS = 1 << 50;
}
}

Expand Down Expand Up @@ -290,6 +292,7 @@ impl RuntimeGlobals {
R::HARMONY_MODULE_DECORATOR => "__webpack_require__.hmd",
R::NODE_MODULE_DECORATOR => "__webpack_require__.nmd",
R::SYSTEM_CONTEXT => "__webpack_require__.y",
R::THIS_AS_EXPORTS => "top-level-this-exports",
r => panic!(
"Unexpected flag `{r:?}`. RuntimeGlobals should only be printed for one single flag."
),
Expand Down
4 changes: 4 additions & 0 deletions crates/rspack_core/src/utils/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,10 @@ pub fn extract_member_expression_chain<'e, T: Into<MaybeExpr<'e>>>(
Expr::Member(ref expr) => {
walk_member_expr(expr, false, members, members_optionals, members_spans, kind)
}
Expr::This(ref this_expr) => {
LingyuCoder marked this conversation as resolved.
Show resolved Hide resolved
members.push_front((JsWord::from("this"), this_expr.span.ctxt));
members_spans.push_front(this_expr.span);
}
Expr::Ident(ref ident) => {
members.push_front((ident.sym.clone(), ident.span.ctxt));
members_spans.push_front(ident.span);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
mod common_js_exports_dependency;
mod common_js_require_dependency;
pub use common_js_exports_dependency::CommonJsExportsDependency;
pub use common_js_exports_dependency::ExportsBase;
pub use common_js_require_dependency::CommonJsRequireDependency;
mod require_resolve_dependency;
pub use require_resolve_dependency::RequireResolveDependency;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl DependencyTemplate for HarmonyCompatibilityDependency {
),
InitFragmentStage::StageAsyncBoundary,
0,
InitFragmentKey::uniqie(),
InitFragmentKey::unique(),
Some(format!("\n__webpack_async_result__();\n}} catch(e) {{ __webpack_async_result__(e); }} }}{});", if matches!(mgm.build_meta.as_ref().map(|meta| meta.has_top_level_await), Some(true)) { ", 1" } else { "" })),
)));
}
Expand Down
14 changes: 11 additions & 3 deletions crates/rspack_plugin_javascript/src/plugin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,17 @@ impl JsPlugin {
execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
"#,
),
false => RawSource::from(
"__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n",
),
false => {
if runtime_requirements.contains(RuntimeGlobals::THIS_AS_EXPORTS) {
LingyuCoder marked this conversation as resolved.
Show resolved Hide resolved
RawSource::from(
"__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n",
)
} else {
RawSource::from(
"__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n",
)
}
}
};

if strict_module_error_handling {
Expand Down
37 changes: 27 additions & 10 deletions crates/rspack_plugin_javascript/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,18 +104,35 @@ fn render_module(
runtime_requirements: Option<&RuntimeGlobals>,
module_id: &str,
) -> Result<BoxSource> {
// TODO unused exports_argument
let module_argument = {
let need_module = runtime_requirements.is_some_and(|r| r.contains(RuntimeGlobals::MODULE));
// TODO: determine arguments by runtime requirements after aligning commonjs dependencies with webpack
// let need_exports = runtime_requirements.is_some_and(|r| r.contains(RuntimeGlobals::EXPORTS));
// let need_require = runtime_requirements.is_some_and(|r| {
// r.contains(RuntimeGlobals::REQUIRE) || r.contains(RuntimeGlobals::REQUIRE_SCOPE)
// });
let need_exports = true;
let need_require = true;

let mut args = Vec::new();
if need_module || need_exports || need_require {
let module_argument = mgm.get_module_argument();
if let Some(runtime_requirements) = runtime_requirements
&& runtime_requirements.contains(RuntimeGlobals::MODULE)
{
args.push(if need_module {
module_argument.to_string()
} else {
format!("__unused_webpack_{module_argument}")
}
};
let exports_argument = mgm.get_exports_argument();
});
}
if need_exports || need_require {
let exports_argument = mgm.get_exports_argument();
args.push(if need_exports {
exports_argument.to_string()
} else {
format!("__unused_webpack_{exports_argument}")
});
}
if need_require {
args.push(RuntimeGlobals::REQUIRE.to_string());
}
let mut sources = ConcatSource::new([
RawSource::from(serde_json::to_string(module_id).map_err(|e| internal_error!(e.to_string()))?),
RawSource::from(": "),
Expand All @@ -124,8 +141,8 @@ fn render_module(
sources.add(RawSource::from(format!("\n/* start::{} */\n", module_id)));
}
sources.add(RawSource::from(format!(
"(function ({module_argument}, {exports_argument}, {}) {{\n",
RuntimeGlobals::REQUIRE
"(function ({}) {{\n",
args.join(", ")
)));
if let Some(build_info) = &mgm.build_info
&& build_info.strict
Expand Down
Loading
Loading