如何在 webpack 中使用 PDFkit 库?

AIo*_*Ion 5 node-pdfkit webpack

我想以编程方式打印一些 pdf 文档。我现在正在努力使这个 PDFkit 库与 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".
Run Code Online (Sandbox Code Playgroud)

然后到

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`
    })
],
Run Code Online (Sandbox Code Playgroud)

};

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

小智 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文件。