3

I'm trying to use the React PDF lib in a project that react created with Vite.

I'm having problems rendering the PDF component and the error is very weird, could someone help me?

Error

Uncaught SyntaxError: The requested module '/node_modules/.vite/@react-pdf_renderer.js?v=3e3d2b30' does not provide an export named 'Document' PDFDocument.tsx:2

// PDFDocument.tsx

import React from 'react';
import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer';

// Create styles
const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4'
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

// Create Document Component
export const PDFDocument = () => (
<Document>
  <Page size="A4" style={styles.page}>
    <View style={styles.section}>
      <Text>Section #1</Text>
    </View>
    <View style={styles.section}>
      <Text>Section #2</Text>
    </View>`
  </Page>`
</Document>`
);
// Document.tsx

import { Box, Button, Flex, Heading, Icon} from '@chakra-ui/react';
import React, { useState } from 'react'; 
import { RiArrowLeftLine } from 'react-icons/ri'; 
import { useNavigate, useParams } from 'react-router-dom'; 
import { PDFDocument } from '../../components/Document/PDFDocument';
import { Header } from '../../components/Header';
    
interface PageNumber { numPages: number | null; } 

export function UserDocument() { 
  const navigate = useNavigate() 
  const { documentId } = useParams()
  
  return ( 
    <Flex direction='column' h='100vh'> 
      <Header />  
      <Flex w='100%' my='6' maxW={1480} mx='auto' px='6'>
        <Flex flexDir='column' w='100%' my='6' maxW={1480} mx='auto' px='6'>
          <Flex
            align='center'
            flexDir='row'
            gap='4'
            mb='6'
          >
              <Button
                onClick={() => navigate(-1)}
                cursor='pointer'
                as="a"
                size='lg'
                fontSize='sm'
                colorScheme='blackAlpha'
                leftIcon={<Icon fontSize='20' as={RiArrowLeftLine}/>}
                >Go back</Button>
            <Heading
              alignSelf='center'
            >Document</Heading>
    
    
          </Flex>
    
          <Box
              p={['6', '8']}
              bg='gray.800'
              borderRadius={8}
              pb='4'
            >
              <PDFDocument />
              
            </Box>
          ); 
    }
            
          </Flex>
      </Flex>
    </Flex>

I tried to install some Vite plugins but I couldn't, I followed the official React PDF documentation.

https://react-pdf.org/

Savas Vedova
  • 5,622
  • 2
  • 28
  • 44
joao gomes
  • 31
  • 1
  • 2

3 Answers3

2

If you get the same error as @jojagames then you should try updating you're dependency to "@react-pdf/renderer":"^3.0.0" and check once. If the errors still exists like Uncaught TypeError: Cannot read properties of undefined (reading 'call') or Uncaught TypeError: EventEmitter3 is undefined , then try the following steps:

My Environment:

"@react-pdf/renderer": "^3.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"@vitejs/plugin-react": "^2.2.0",
"vite": "^3.2.0"

Solution:

  1. Add the following dependencies by running the command:
yarn add --dev @esbuild-plugins/node-modules-polyfill @esbuild-plugins/node-globals-polyfill
  1. Update the vite.config.js file:
import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
import {NodeGlobalsPolyfillPlugin} from '@esbuild-plugins/node-globals-polyfill'
import {NodeModulesPolyfillPlugin} from '@esbuild-plugins/node-modules-polyfill'
// You don't need to add this to deps, it's included by @esbuild-plugins/node-modules-polyfill
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'


// https://vitejs.dev/config/
export default defineConfig({
    plugins: [react()],
    resolve: {
        alias: {
            // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill,
            // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
            // process and buffer are excluded because already managed
            // by node-globals-polyfill
            util: 'rollup-plugin-node-polyfills/polyfills/util',
            sys: 'util',
            events: 'rollup-plugin-node-polyfills/polyfills/events',
            stream: 'rollup-plugin-node-polyfills/polyfills/stream',
            path: 'rollup-plugin-node-polyfills/polyfills/path',
            querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
            punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
            url: 'rollup-plugin-node-polyfills/polyfills/url',
            string_decoder:
                'rollup-plugin-node-polyfills/polyfills/string-decoder',
            buffer: 'rollup-plugin-node-polyfills/polyfills/buffer-es6',
            process: 'rollup-plugin-node-polyfills/polyfills/process-es6',
            http: 'rollup-plugin-node-polyfills/polyfills/http',
            https: 'rollup-plugin-node-polyfills/polyfills/http',
            os: 'rollup-plugin-node-polyfills/polyfills/os',
            assert: 'rollup-plugin-node-polyfills/polyfills/assert',
            constants: 'rollup-plugin-node-polyfills/polyfills/constants',
            _stream_duplex:
                'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
            _stream_passthrough:
                'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
            _stream_readable:
                'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
            _stream_writable:
                'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
            _stream_transform:
                'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
            timers: 'rollup-plugin-node-polyfills/polyfills/timers',
            console: 'rollup-plugin-node-polyfills/polyfills/console',
            vm: 'rollup-plugin-node-polyfills/polyfills/vm',
            zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
            tty: 'rollup-plugin-node-polyfills/polyfills/tty',
            domain: 'rollup-plugin-node-polyfills/polyfills/domain'
        }
    },
    optimizeDeps: {
        esbuildOptions: {
            // Node.js global to browser globalThis
            define: {
                global: 'globalThis'
            },
            // Enable esbuild polyfill plugins
            plugins: [
                NodeGlobalsPolyfillPlugin({
                    process: true,
                    buffer: true
                }),
                NodeModulesPolyfillPlugin()
            ]
        }
    },
    build: {
        rollupOptions: {
            plugins: [
                // Enable rollup polyfills plugin
                // used during production bundling
                rollupNodePolyFill()
            ]
        }
    }
})

There you go, now you should be able to utilize the @react-pdf/renderer dependency in react 18 with the vite. I was able to successfully create a build without any error. Here is the github repo for reference.

For more info about the error on the node polyfill with vite, try this answer.

Kudos to @fabiano-taioli, @jifus.

Ashfaq nisar
  • 2,500
  • 1
  • 12
  • 22
1

I had the same issue and vite plugins don't work currently. I fixed this import error with this, adding a file "reactPdf.js" like follows to my project that "converts" the default export to named exports:

import pdf from '@react-pdf/renderer'

export const StyleSheet = pdf.StyleSheet
export const Font = pdf.Font

// https://react-pdf.org/components
export const Document = pdf.Document
export const Page = pdf.Page
export const Image = pdf.Image
export const View = pdf.View
export const Text = pdf.Text
export const Link = pdf.Link
export const Note = pdf.Note
export const Canvas = pdf.Canvas

// https://react-pdf.org/svg
export const Svg = pdf.Svg
export const Line = pdf.Line
export const Polyline = pdf.Polyline
export const Polygon = pdf.Polygon
export const Path = pdf.Path
export const Rect = pdf.Rect
export const Circle = pdf.Circle
export const Ellipse = pdf.Ellipse
// export const Text = pdf.Text
export const Tspan = pdf.Tspan
export const G = pdf.G
export const Stop = pdf.Stop
export const Defs = pdf.Defs
export const ClipPath = pdf.ClipPath
export const LinearGradient = pdf.LinearGradient
export const RadialGradient = pdf.RadialGradient

And then I can import from that file normally:

import { Document, Page, Text } from './reactPdf.js'

I got help from git hub name @carlobeltrame in this page https://github.com/diegomura/react-pdf/issues/1317

1

Have you followed all steps in the right order?

yarn package

yarn add --dev vite-plugin-shim-react-pdf

vite.config.js modifications

import { defineConfig } from "vite";
import reactRefresh from "@vitejs/plugin-react-refresh";
import shimReactPdf from "vite-plugin-shim-react-pdf";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [reactRefresh(), shimReactPdf()],
});

imports

import pdf from "@react-pdf/renderer";
const { Document, Text, View, StyleSheet } = pdf;
Ahmet Firat Keler
  • 2,603
  • 2
  • 11
  • 22