【问题标题】:How to use PDFkit library with webpack?如何在 webpack 中使用 PDFkit 库?
【发布时间】:2017-10-01 07:23:16
【问题描述】:

我想以编程方式打印一些 pdf 文档。我现在正在尝试几个小时让 this PDFkit library 与 webpack 一起工作。

我已经离开了:

Can't resolve 'fs' in ..

fs.readFileSync is not a function

然后到警告

[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 is not defined - 我被困在这里了。所有这些错误都来自库本身。

我只有一个文件 - 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`
    })
],

};

这实际上是一个 1 行应用程序,我现在已经碰壁了好几个小时。我已经看到许多用户在使用fs 核心模块和webpack 时遇到问题——我尝试了所有能找到的解决方案。它能有多难?这里实际发生了什么?任何见解都表示赞赏,谢谢。

【问题讨论】:

    标签: webpack node-pdfkit


    【解决方案1】:

    可以让它与 webpack 一起工作。

    pdfmakepdfkit 的包装器,可与 webpack 一起使用。如您所见,webpack.config.js 有点老套:

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

    就个人而言,我最终使用了 pdfmake,它提供了一个内置的 js 文件。 如果你这样做,你将不得不调整你的 webpack.config,使用 resolve.alias 字段指向 pdfmake 构建的 js 文件。

    【讨论】:

      【解决方案2】:

      如果你想直接使用构建版本,只需使用:

      window.pdfMake = require('pdfmake/build/pdfmake.js');
      var vfs = require('pdfmake/build/vfs_fonts.js');
      window.pdfMake.vfs = vfs.pdfMake.vfs;
      

      【讨论】:

        【解决方案3】:

        对于下一个遇到这个问题的可怜人来说,fs.readFileSync 提到的第一个问题几乎可以肯定是这个问题:PDFKit - Custom Fonts - fs.readFileSync is not a function

        问题中的这一行是这部分谜题的关键:

        { test: /pdfkit|png-js/, loader: "transform-loader?brfs" }
        

        我最终放弃了这一点,只是在 webpack 之外导入了构建的发布文件(来自 https://github.com/foliojs/pdfkit/releases)(即使用脚本 src="" 引用静态 .js 文件)

        【讨论】:

        • 我试图这样做,但我在npm start 上得到了JavaScript heap out of memory
        【解决方案4】:

        您也可以将其添加到外部:

          externals: [
            {
              pdfkit: "commonjs2 pdfkit",
            }
          ]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-14
          • 2020-02-22
          • 1970-01-01
          • 2015-02-20
          • 1970-01-01
          相关资源
          最近更新 更多