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\repos\Frontend\src\views\default\components\Footer.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\repos\Frontend\src\views\default\components @ ./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?
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]'
}
}
]
}
And just a reminder to quit webpack (Ctrl+C in powershell) and restart it again for the config to take effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With