如何在webpack中使用PDFkit库?

5
我想通过编程的方式打印一些PDF文档。我已经花费了数小时的时间尝试使用Webpack使PDFkit库(这个库)正常工作。

我从以下错误开始:

在..中找不到“fs”

然后是:

fs.readFileSync不是一个函数

最后出现了警告。

[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".

然后到

require未定义 - 我卡在这里了。所有这些错误都来自库内部。

我只有一个文件 - app.js,只有一行代码

const PDFDocument = require('pdfkit');

我的最终webpack.config.js看起来像这样:

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`
    })
],

这是一个只有一行代码的应用程序,我现在已经遇到了几个小时的问题。我看到许多用户遇到了关于fs核心模块和webpack的问题 - 我尝试了我能找到的每一个解决方案。这到底有多难?实际上发生了什么?感谢任何见解。
4个回答

3
您可以将其添加到外部文件中:
  externals: [
    {
      pdfkit: "commonjs2 pdfkit",
    }
  ]

1

可以使用Webpack让它工作。

pdfmake是一个包装在pdfkit周围的工具,可以与Webpack一起使用。正如您所看到的,webpack.config.js有点hacky:

https://github.com/bpampuch/pdfmake/blob/master/webpack.config.js

个人而言,我最终选择了使用pdfmake,并提供了一个内置的js文件。如果您这样做,您将需要调整您的webpack.config,使用resolve.alias字段指向pdfmake构建的js文件。

0

我尝试做这个,但在“npm start”时出现了“JavaScript heap out of memory”。 - GuiRitter

0
如果您想直接使用构建版本,请使用以下命令:
window.pdfMake = require('pdfmake/build/pdfmake.js');
var vfs = require('pdfmake/build/vfs_fonts.js');
window.pdfMake.vfs = vfs.pdfMake.vfs;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接