Skip to content

Commit 60dfc2c

Browse files
authored
fix(transform-imports): Transform side-effect imports (#473)
Closes: #474 --- [Original issue](#329): Imports with side effects were being incorrectly removed. The expected behavior is to retain the import and apply the transformation. The current behavior causes issues when the code includes TypeScript side-effect imports. These are skipped by the plugin and remain untransformed, which leads to runtime failures in Node.js (since it cannot import .ts files directly).
1 parent f9213d3 commit 60dfc2c

4 files changed

Lines changed: 25 additions & 4 deletions

File tree

.changeset/old-papayas-destroy.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@swc/plugin-transform-imports": patch
3+
---
4+
5+
fix(transform-imports): Transform side-effect imports

packages/transform-imports/__tests__/__snapshots__/wasm.test.ts.snap

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export { default as Footer } from "my-library/components/App/Footer";
6363
`;
6464

6565
exports[`Should load transform-imports wasm plugin correctly > Should transform side-effect-imports correctly 1`] = `
66-
"import './upload/upload.ts';
66+
"import './upload/upload.js';
6767
import './scripts/scripts.model.js';
6868
"
6969
`;

packages/transform-imports/transform/src/lib.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -381,9 +381,25 @@ impl VisitMut for TransformImports<'_> {
381381
for item in module.body.take() {
382382
match item {
383383
ModuleItem::ModuleDecl(ModuleDecl::Import(decl)) => {
384-
// Ignore side-effect only imports
385384
if decl.specifiers.is_empty() {
386-
new_items.push(ModuleItem::ModuleDecl(ModuleDecl::Import(decl)));
385+
if let Some(rewriter) = self.should_rewrite(&decl.src.value) {
386+
let new_path = rewriter.new_path(None);
387+
let raw_with_quotes = Atom::from(format!("'{}'", new_path.as_ref()));
388+
let new_src = Box::new(Str {
389+
span: decl.src.span,
390+
value: new_path.clone(),
391+
raw: Some(raw_with_quotes),
392+
});
393+
let new_decl = ImportDecl {
394+
src: new_src,
395+
specifiers: vec![],
396+
..decl
397+
};
398+
399+
new_items.push(ModuleItem::ModuleDecl(ModuleDecl::Import(new_decl)));
400+
} else {
401+
new_items.push(ModuleItem::ModuleDecl(ModuleDecl::Import(decl)));
402+
}
387403
continue;
388404
}
389405

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
import './upload/upload.ts';
1+
import './upload/upload.js';
22
import './scripts/scripts.model.js';

0 commit comments

Comments
 (0)