0

General recommendation for processing a PDF file in Webpack keeps pointing me back to: https://webpack.js.org/loaders/file-loader/

Webpack documentation doesn't really explain static generation, and Next's config documentation doesn't really explain file loading for PDFs.

I put my PDFs into Next's /public folder and when I run yarn build the file paths are generated as /public/file-name.pdf, which is what I asked for. However, all of those links are dead. I think this might have to do with the way Next bundles things under the hood but that isn't explained anywhere I can find.

I've cobbled the following together, anyone have a sense of where I'm going wrong?

// next.config.js
const withPlugins = require('next-compose-plugins')
const withImages = require('next-images')

const { 
  PHASE_DEVELOPMENT_SERVER, 
  PHASE_PRODUCTION_BUILD 
} = require('next/constants')

const nextConfig = {
  webpack: (config, options) => {
 
    config.module.rules.push({
      test: /\.pdf$/,
      use: [
        {
          loader: 'file-loader',
          options: {
            name: '[path][name].[ext]',
            outputPath: '/public'
          }
        } 
      ]
    })
 
    return config;
  }
}
module.exports = withPlugins([
  [withImages, {
    [PHASE_DEVELOPMENT_SERVER]: 'http://localhost:3001',
    [PHASE_PRODUCTION_BUILD]: 'https://www.example.com'
  }]
], nextConfig)
serraosays
  • 7,163
  • 3
  • 35
  • 60
  • Probably a stupid question, but can't you just put them into the public folder? – Gh05d Jan 28 '21 at 13:27
  • @Gh05d - yeah that's where they are. But webpack has to process them for deployment and bundle, so you need some webpack middleware to make that happen. – serraosays Jan 28 '21 at 14:14
  • Ah, ok. Maybe webpack does not check the public folder in nextjs? Isn't there a parameter you can pass to the loader which contains the path to the pdfs? – Gh05d Jan 28 '21 at 14:47
  • If you want webpack to process the files you need to reference them somewhere in your code. Otherwise, simply having the pdfs in your `public/` folder should make them publicly available on your website. – juliomalves Jan 28 '21 at 18:20
  • @Gh05d - you would think Next exposes the default public directory but I haven't seen how to access it. – serraosays Jan 29 '21 at 16:19
  • @juliomalves - read my updated response above – serraosays Jan 29 '21 at 16:19

0 Answers0