How to fix Vite build / parser error "Unexpected token" in third party dependencies?
Asked Answered
R

3

11

I'm trying to create a production build of my React application with Vite. When I run the npm run dev command, the app will start and seems to work as it should, but during the build I always get these kind of parser errors by some third party dependencies, telling that it includes an unexpected token.

Am I missing something in my config file or what could it be?

❯ npm run build

> project build
> tsc && vite build

vite v2.9.12 building for production...
✓ 4 modules transformed.
[commonjs] Unexpected token (1:20) in /Users/../node_modules/react-router-dom/index.js
file: /Users/../node_modules/react-router-dom/index.js:1:20
1: /**
      ^
2:  * React Router DOM v6.3.0
3:  *
error during build:
SyntaxError: Unexpected token (1:20) in /Users/../node_modules/react-router-dom/index.js
    at Parser.pp$4.raise (/Users/../node_modules/rollup/dist/shared/rollup.js:19740:13)
    at Parser.pp$9.unexpected (/Users/../node_modules/rollup/dist/shared/rollup.js:17034:8)
    at Parser.pp$5.parseIdent (/Users/../node_modules/rollup/dist/shared/rollup.js:19671:10)
    at Parser.pp$8.parseImportSpecifiers (/Users/../node_modules/rollup/dist/shared/rollup.js:18117:27)
    at Parser.pp$8.parseImport (/Users/../node_modules/rollup/dist/shared/rollup.js:18078:28)
    at Parser.pp$8.parseStatement (/Users/../rollup/dist/shared/rollup.js:17210:49)
    at Parser.pp$8.parseTopLevel (/Users/../node_modules/rollup/dist/shared/rollup.js:17091:21)
    at Parser.parse (/Users/../node_modules/rollup/dist/shared/rollup.js:16863:15)
    at Function.parse (/Users/../node_modules/rollup/dist/shared/rollup.js:16913:35)
    at Graph.contextParse (/Users/m../node_modules/rollup/dist/shared/rollup.js:23017:38)

The project was initialized with React and TypeScript. I had to configure polyfills for several libs that required node dependencies. The vite.config.ts looks like this:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import * as path from 'path';
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill';
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill';
import polyfillNode from 'rollup-plugin-polyfill-node';

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [react(), polyfillNode()],

    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src'),
            util: 'rollup-plugin-node-polyfills/polyfills/util',
            events: 'rollup-plugin-node-polyfills/polyfills/events',
            stream: 'rollup-plugin-node-polyfills/polyfills/stream',
            path: 'rollup-plugin-node-polyfills/polyfills/path',
            zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
        },
    },

    define: {
        // By default, Vite doesn't include shims for NodeJS/
        // necessary for segment analytics lib to work
        global: {},
        process: { env: { HOME: './src' } },
    },

    server: {
        host: true,
        port: 5001,
        hmr: { host: 'localhost' },
        proxy: {
            '/api': {
                target: 'http://localhost:3001',
                changeOrigin: true,
                secure: false,
                rewrite: (path) => path.replace(/^\/api/, ''),
            },
        },
    },

    optimizeDeps: {
        esbuildOptions: {
            // Node.js global to browser globalThis
            define: {
                global: 'globalThis',
            },
            // Enable esbuild polyfill plugins
            plugins: [
                NodeGlobalsPolyfillPlugin({
                    process: true,
                    buffer: true,
                }),
                NodeModulesPolyfillPlugin(),
            ],
        },
    },

    build: {
        commonjsOptions: {
            transformMixedEsModules: true,
        },
        rollupOptions: {
            output: {
                dir: 'output',
                format: 'cjs',
            },
            plugins: [
                // Enable rollup polyfills plugin
                // used during production bundling
                polyfillNode(),
            ],
        },
    },
});

Here is the package.json:

{
    "scripts": {
        "dev": "vite",
        "build": "tsc && vite build",
        "preview": "vite preview"
    },
    "dependencies": {
        "@emotion/react": "^11.9.3",
        "@emotion/styled": "^11.9.3",
        "@esbuild-plugins/node-globals-polyfill": "^0.1.1",
        "@esbuild-plugins/node-modules-polyfill": "^0.1.4",
        "@mui/icons-material": "^5.8.4",
        "@mui/lab": "^5.0.0-alpha.87",
        "@mui/material": "^5.8.5",
        "@mui/x-date-pickers": "^5.0.0-alpha.6",
        "@react-pdf/renderer": "^2.2.0",
        "@types/luxon": "^2.3.2",
        "amazon-cognito-identity-js": "^5.2.9",
        "axios": "^0.27.2",
        "draft-js": "^0.11.7",
        "events": "^3.3.0",
        "luxon": "^2.4.0",
        "preval.macro": "^5.0.0",
        "react": "^18.0.0",
        "react-beautiful-dnd": "^13.1.0",
        "react-dom": "^18.0.0",
        "react-draft-wysiwyg": "^1.14.7",
        "react-dropzone": "^14.2.1",
        "react-redux": "^8.0.2",
        "react-router-dom": "^6.3.0",
        "redux-logger": "^3.0.6",
        "rollup-plugin-polyfill-node": "^0.9.0",
        "stream": "^0.0.2",
        "util": "^0.12.4",
        "uuid": "^8.3.2",
        "zlib": "^1.0.5"
    },
    "devDependencies": {
        "@reduxjs/toolkit": "^1.8.2",
        "@rollup/plugin-commonjs": "^22.0.1",
        "@testing-library/jest-dom": "^5.16.4",
        "@testing-library/react": "^13.3.0",
        "@types/draft-js": "^0.11.9",
        "@types/jest": "^28.1.3",
        "@types/node": "^18.0.0",
        "@types/preval.macro": "^3.0.0",
        "@types/react": "^18.0.0",
        "@types/react-beautiful-dnd": "^13.1.2",
        "@types/react-dom": "^18.0.0",
        "@types/react-draft-wysiwyg": "^1.13.4",
        "@types/react-redux": "^7.1.24",
        "@types/react-router-dom": "^5.3.3",
        "@types/redux-logger": "^3.0.9",
        "@types/uuid": "^8.3.4",
        "@vitejs/plugin-react": "^1.3.0",
        "jest": "^28.1.1",
        "typescript": "^4.6.3",
        "vite": "^2.9.9"
    }
}
Ravenous answered 29/6, 2022 at 4:2 Comment(0)
P
4

I was encountering a similar issue but fixed by adding below line to the top of my entry file (which was main.ts in vue project)

window.global ||= window;

Make sure to add that before any imports.

Be sure to remove defition of global from vite.config.ts

global: {} // Delete this
Pharmacy answered 9/6, 2023 at 12:16 Comment(1)
Thanks, @Light Yagami for this quick fix! Upvoted.Estrada
A
2

I think you should use global: '({})' rather than global: {} in vite.config.ts

Check out the link below for more details. https://github.com/vitejs/vite/issues/8909

Achlamydeous answered 6/7, 2022 at 2:23 Comment(2)
I had to do something similar for process.env: "process.env": `(${JSON.stringify(process.env)})`Plesiosaur
@Plesiosaur this fixed it for me; thanks!Schizothymia
P
0

The

window.global ||= window;

worked for me for run the final build but returned the vite problem for the dev running

for both work well I guess is necessary a third solution, maybe using the vite.config.js

Postprandial answered 6/7, 2023 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.