Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PDFkit library with webpack?

I want to print some pdf documents programmatically. and I'm trying for hours now to make this PDFkit library working with webpack.

I've gone form:

Can't resolve 'fs' in ..

to

fs.readFileSync is not a function

then to the warning

[BABEL] Note: The code generator has deoptimised the styling of "E:/MyProjects/accountingsystem/node_modules/brotli/dec/dictionary-da
ta.js" as it exceeds the max of "500KB".

then to

require is not defined - i'm stuck here. All this errors are coming form within the library itself.

I have just one file - app.js with just a single line of code, which is:

const PDFDocument = require('pdfkit');

My final webpack.config.js looks like this:

module.exports = {
// devtool: 'source-map',

entry: './src/app.js',
output: {
    path: path.resolve (__dirname, "dist"),
    filename: "bundle.js"
},

// node: {
//     console: true,
//     fs: 'empty',
//     net: 'empty',
//     tls: 'empty'
// },

// i've added 'target' - following the advice form some github comments.
target: 'node',
module : {
    rules : [
        { test: /\.js$/, loader: 'babel-loader' },
        {
            test : /\.html$/,
            use : [ 'html-loader' ]
        },

        // then i've added this 2 loaders also:
        { test: /\.json$/, loader: 'json-loader' },
        { test: /pdfkit|png-js/, loader: "transform-loader?brfs" }
    ]
},
plugins:[
    new HtmlWebpackPlugin ({
          template : `src/app.html`
    })
],

};

This is literally a 1 line app, and i'm hitting the wall for hours now. I've seen that many users are having issues with fs core module and webpack - and i tried every solution i could find. How hard can it be? What is actually happening here? Any insight is appreciated, Thanks.

like image 227
AIon Avatar asked Oct 29 '22 08:10

AIon


1 Answers

You can also add it to the externals:

  externals: [
    {
      pdfkit: "commonjs2 pdfkit",
    }
  ]
like image 55
rasgo Avatar answered Nov 21 '22 04:11

rasgo