vitejs/vite-plugin-react-swc

Error when importing multiple different exports with the same name from different modules (namespaced)

elbojoloco opened this issue · 3 comments

This error occurred only after switching from the regular react plugin to the react-swc plugin. The exact error is:
Uncaught SyntaxError: The requested module '/src/types/devices.ts?t=1692279660309' does not provide an export named 'Device' (at AddDevicePopup.tsx:11:10)

In my scenario I have a React component that imports a type and a styled component with the same name:

AddDevicePopup.tsx

import { Device } from '@types/devices';
import * as S from "./AddDevicePopup.styled"; // includes S.Device

devices.ts

export type Device = {};

AddDevicePopup.styled

export const Device = styled.button;

It seems that even though the styled component Device is imported under the namespace S it somehow collides with the exported type Device and breaks my app. When renaming either the exported type or the styled component it works fine. So the workaround is easy but this seems like an issue that should resolved.

My guess from the code snippets is the file doesn't contains enough information to decide if import { Device } from '@types/devices'; is a type import or not and Babel default to type import and SWC to runtime import which fails.

A good solution to avoid that is to enable the new compiler flag verbatimModuleSyntax which forces you to be explicit on type imports which simplify the transpilation by other tools that can safely drop import statements

Sorry for the late response, got lost in the notifications.

So you suggest I start using the following syntax to import types to avoid these edge cases?

import type { Device } from '@types/devices';

Yes this is the simplest solution.
If it's used in the file, this is probably an SWC bug. If this just re-exported, this is best to change the other importers to import directly from @types/devices. This is better for Vite HMR because when you edit a file the is more explicit which which modules depends on it.