Skip to content

Commit dff9b9b

Browse files
committed
Don't put anything before ES module imports
Because of some incorrect use of `js.push_str(..)`, we could sometimes emit code before the ES modules imports, which is syntactically invalid: const __exports = {}; import { Thing } from '...'; // Syntax error! This has been fixed by making sure that the correct `imports` or `imports_post` string is built up. We now also assert that the `js` string is empty at the location where we add imports if we're using ES modules.
1 parent 863a8b9 commit dff9b9b

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

crates/cli-support/src/js/mod.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,8 @@ impl<'a> Context<'a> {
354354
| OutputMode::Node {
355355
experimental_modules: true,
356356
} => {
357-
js.push_str(&format!("import * as wasm from './{}_bg';\n", module_name));
357+
self.imports
358+
.push_str(&format!("import * as wasm from './{}_bg';\n", module_name));
358359
if needs_manual_start {
359360
self.footer.push_str("wasm.__wbindgen_start();\n");
360361
}
@@ -365,7 +366,7 @@ impl<'a> Context<'a> {
365366
// expose the same initialization function as `--target no-modules`
366367
// as the default export of the module.
367368
OutputMode::Web => {
368-
js.push_str("const __exports = {};\n");
369+
self.imports_post.push_str("const __exports = {};\n");
369370
self.imports_post.push_str("let wasm;\n");
370371
init = self.gen_init(&module_name, needs_manual_start);
371372
self.footer.push_str("export default init;\n");
@@ -377,6 +378,10 @@ impl<'a> Context<'a> {
377378
ts.push_str(&init_ts);
378379

379380
// Emit all the JS for importing all our functionality
381+
assert!(
382+
!self.config.mode.uses_es_modules() || js.is_empty(),
383+
"ES modules require imports to be at the start of the file"
384+
);
380385
js.push_str(&self.imports);
381386
js.push_str("\n");
382387
js.push_str(&self.imports_post);

crates/cli-support/src/lib.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,19 @@ enum OutputMode {
4242
Node { experimental_modules: bool },
4343
}
4444

45+
impl OutputMode {
46+
fn uses_es_modules(&self) -> bool {
47+
match self {
48+
OutputMode::Bundler { .. }
49+
| OutputMode::Web
50+
| OutputMode::Node {
51+
experimental_modules: true,
52+
} => true,
53+
_ => false,
54+
}
55+
}
56+
}
57+
4558
enum Input {
4659
Path(PathBuf),
4760
Module(Module, String),

0 commit comments

Comments
 (0)