无法使用 webpack 和 React 解析“fs”

问题描述 投票:0回答:4

当我尝试为我的节点服务器构建应用程序时,我不断收到描述中的错误。

我最终试图读取 docxtemplater 的 .docx 文件,但如果没有“fs”工作,它看起来就不那么明亮。

我尝试使用我在许多解决方案中看到的节点:{fs:“empty”}解决方法,但当我在浏览器上运行它时,它仍然给我相同的错误或传播到控制台。

这是我的 webpack.config.js 中的内容:

var path = require('path');
var webpack = require('webpack');
//var HtmlWebpackPlugin = require('html-webpack-plugin');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');

const sourcePath = path.join(__dirname, './front_end');
const buildPath = path.join(__dirname, './src/bin');

module.exports = {
    devtool: 'source-map',
    //home directory for webpack must be absolute
    //context: sourcePath,
    //Application Execution and Webpack Bundling
    entry: {
        js: path.join(sourcePath, 'index.js')
        //html: './index.html',
    },
    output: {
        //Must be absolute path
        path: sourcePath,
        //publicPath: buildPath,
        //publicPath: path.join(__dirname, '/src/bin'),
        filename: "bundle.js"
    },

    resolve: {
        extensions: [
            '.webpack-loader.js',
            '.web-loader.js',
            '.loader.js',
            '.js',
            '.jsx'
        ],
        modules: [
            path.join(__dirname),
            "node_modules"
        ],
    },
    module: {
        rules: [
            {
                test: /\.js$|\.jsx$/,
                exclude: /node_modules/,
                use: [
                    "babel-loader",
                    "eslint-loader",
                ]
            },
            {
                test: /\.html/,
                exclude: /node_modules/,
                use: [
                    "file-loader",
                ]
            },
            {
                test: /\.css/,
                exclude: /node_modules/,
                use: [
                    "style-loader",
                    'css-loader'
                ]
            },
            {
                test: /\.(gif|png)/,
                exclude: /node_modules/,
                use: [
                    "url-loader"
                ]
            }
        ],
        loaders: [
            {
                test: /\.js$|\.jsx$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2016', 'react']
                }
            },
            {
                test: /\.css$/,
                loader: 'style-loader',
                use: ['style-loader', 'css-loader'],
                exclude: /node_modules/
            },
            {
                test: /\.html$/,
                loader: "file?name=[name].[ext]"
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loaders: [
                    'file?hash=sha512&digest=hex&name=[hash].[ext]',
                    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
                ]
            }
        ]
    },
    plugins: [
     ],
    stats: {
        assets: true,
        colors: true,
        errors: true,
        errorDetails: true,
        hash: true,
    }
};
node.js webpack fs docxtemplater
4个回答
16
投票

您无法在浏览器中使用 Node Core API 附带的任何模块,它们在那里不起作用。 Node Core 模块依赖于浏览器中不存在的 C/C++ 二进制文件。因此,您需要找到一种等效的方法来替换 React 应用程序中的任何

fs
使用。

一种方法是通过 Node JS 后端将您想要通过 HTTP 使用的文件提供给您的 React 应用程序。您可以在 Node 服务器中使用

fs
读取文件,并将该逻辑放置在路由中,通过 HTTP 从 React 应用程序调用该路由并将其流式传输回来。然后,您将在 React 应用程序中拥有文件数据,并可以根据需要使用它。

此 GitHub 存储库 包含 Webpack 已移植以供浏览器使用的 Node 核心库列表。不幸的是

fs
不是其中之一。


7
投票

在package.json中添加

  "browser": {
    "crypto": false,
    "fs": false,
    "path": false,
    "os": false,
    "net": false,
    "stream": false,
    "tls": false
    },

在webpack中添加:

node: { fs: 'empty' },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window

0
投票

我来晚了,但这是 docxtemplater 特定的。

要加载 docx,请在节点中使用

fs
,在浏览器中使用
JSZipUtils.getBinaryContent

查看此演示(从此处:http://docxtemplater.readthedocs.io/en/latest/generate.html#browser

<html>
    <script src="docxtemplater.js"></script>
    <script src="jszip.js"></script>
    <script src="vendor/file-saver.min.js"></script>
    <script src="vendor/jszip-utils.js"></script>
    <!--
    Mandatory in IE 6, 7, 8 and 9.
    -->
    <!--[if IE]>
        <script type="text/javascript" src="examples/vendor/jszip-utils-ie.js"></script>
    <![endif]-->
    <script>
    function loadFile(url,callback){
        JSZipUtils.getBinaryContent(url,callback);
    }
    loadFile("examples/tag-example.docx",function(error,content){
        if (error) { throw error };
        var zip = new JSZip(content);
        var doc=new Docxtemplater().loadZip(zip)
        doc.setData({
            first_name: 'John',
            last_name: 'Doe',
            phone: '0652455478',
            description: 'New Website'
        });

        try {
            // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
            doc.render()
        }
        catch (error) {
            var e = {
                message: error.message,
                name: error.name,
                stack: error.stack,
                properties: error.properties,
            }
            console.log(JSON.stringify({error: e}));
            // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
            throw error;
        }

        var out=doc.getZip().generate({
            type:"blob",
            mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        }) //Output the document using Data-URI
        saveAs(out,"output.docx")
    })
    </script>
</html>

0
投票

对我来说,发生这种情况是因为我将

tailwind.config.js
导入到前端代码中以从中解析一些变量(使用“tailwindcss/resolveConfig”)。由于我的配置有导入
fs
的插件 - 我收到了该错误。所以我只是将纯配置数据和插件代码分开。我的
tailwind.config.js
现在导入并合并两者(数据+插件),并且JS应用程序仅导入数据文件(没有使用禁止依赖项的插件)

© www.soinside.com 2019 - 2024. All rights reserved.