create-react-appes6-modulesvitecommonjs

Vite CommonJS Resolver throws Unexpected Token Error when importing ESM


I have a create-react-app project I'm migrating to Vite. That project uses "styled-components" like this:

import styled from 'styled-components';

const someDiv = styled.div`...`;

Now the issue comes up when running vite build:

vite v4.0.2 building for production...
✓ 51 modules transformed.
[commonjs--resolver] Unexpected token (1:167492) in /project/node_modules/styled-components/dist/styled-components.browser.esm.js
file: /project/node_modules/styled-components/dist/styled-components.browser.esm.js:1:167492
1: import{typeOf as e,isElement as t,isValidElementType as n}from"react-is";import r,{useState as o,useContext as i,useMemo as s,useEffect as a,useRef as c,createElement as u,useDebugValue as l,useLayoutEffect as d}from"react";import h from"shallowequal";import p from"@emotion/stylis";import f from"@emotion/unitless";import m from"@emotion/is-prop-valid";import y from"hoist-non-react-statics";function // ... rest of file

So it seems like it is trying to import styled-components.browser.esm.js using the commonjs--resolver, but there are import statements at the top of that file and it seems to get confused.

Any ideas why the "Unexpected token" error might happen and how this can be resolved? Shouldn't it import it as ESM?

UPDATE 07/02/2023: On a Github discussion it was noticed by someone else, that everything works when there is no define block in the vite.config.ts: https://github.com/vitejs/vite/discussions/11495. However, this is a questionable solution if you actually need to define something there.


Solution

  • I opened a bug report with Vite and it turns out the issues is about how define works, it string-replaces the word "process" everywhere with what is put into define in the vite config, leading to the syntax/token errors.

    Detailed answer is here: https://github.com/vitejs/vite/issues/12246#issuecomment-1450153095