Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm serving up some static files like images and fonts, without any problem. When I try to do the same with a PDF file, I get an Error.

ERROR in ./src/views/default/components/Footer.js

c:Resurs eposFrontendsrcviewsdefaultcomponentsFooter.js 5:17 error Parse errors in imported module 'src/includes/ANVANDARAVTAL_MITTKONTOR.pdf' import/default

? 1 problem (1 error, 0 warnings)

ERROR in ./src/views/default/components/Footer.js Module not found: Error: Cannot resolve module 'application-loader' in c:Resurs eposFrontendsrcviewsdefaultcomponents @ ./src/views/default/components/Footer.js 21:32-84

The webpack config works fine, with all the loaders for jsx, es6, css, static files... except for the loader config for PDF.

{
    test: /.pdf(?v=[0-9].[0-9].[0-9])?$/,
    loader: 'file-loader?minetype=application/pdf&name=[name].pdf'
}

My other loader config, that works, looks virtually the same for PDFs, AND WORKS... WHY (SOBBING)!? Ex:

{
    test: /.(ttf|eot|svg)(?v=[0-9].[0-9].[0-9])?$/,
    loader: 'file-loader'
}

The import of files into react component looks like this:

import bg from "src/design/images/loginBG.jpg"; //works fine
import pdf from "src/includes/ANVANDARAVTAL_MITTKONTOR.pdf"; //NOT WORKING!

I've tried so many configurations, googled the error, googled for loaders that could solve the problem. Nothing about serving static content from webpack/react, except the usual images, css, js.

I also tried serving a txt file just to see if it works. This also fails with the same error as the PDF.

Why does webpack try to parse the files when using the file loader?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
593 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use the webpack file-loader module to process static content during production or development and successfully use PDFs. Here is a simplified version of the process:

React component

in your component file first import pdf file like:

import PdfFile from '../../src/file.pdf'

and then change the href attribute:

<a href={PdfFile} target='_blank' >
    <p>Click to open PDF file in a new tab</p>
</a>

Webpack loader

define the webpack rule like:

{
  test: /.(pdf|gif|png|jpe?g|svg)$/,
  use: 'file-loader?name=[path][name].[ext]',
  include: paths
}

or

{
    test: /.(png|svg|jpg|gif|pdf)$/,
    use: [
      {
        loader: 'file-loader',
        options: {
          name: '[name].[ext]'
        }
      }
    ]
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...