无法使用Webpack和React解决“fs”问题

7

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

我最终想要读取一个.docx文件以供docxtemplater使用,但是由于'fs'无法正常工作,这看起来并不太好。

我已经尝试使用node:{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,
    }
};

没有“文件系统”可以从中加载数据,因此如果您需要在Web上使用该数据,则需要重写逻辑,以便通过调用服务器来请求该数据,或者使用浏览器通过<img><link>等加载资源的能力,或者使用特殊的加载程序将它们捆绑在一起。 - Mike 'Pomax' Kamermans
4个回答

17

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

一种方法是通过Node JS后端通过HTTP提供要处理的文件给React应用程序。您可以在Node服务器中使用fs读取文件,并将该逻辑放置在路由中,通过HTTP从React应用程序调用该路由并流式传输回来。然后,您就可以在React应用程序中拥有文件数据,并根据需要进行处理。

这个GitHub存储库列出了Webpack为浏览器使用移植的Node核心库。不幸的是,fs不是其中之一。


1
这对我很有帮助,@peteb -- 谢谢 :) - RancheroBeans

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

6
在Webpack 5中,"node: { fs: 'empty' }"不再起作用。 - jeyko

0

我来晚了,但这与docxtemplater有关。

要加载docx,你可以在node中使用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>

-1
对我来说,这个问题是因为我在前端代码中导入了 `tailwind.config.js`,以便从中解析一些变量(使用 'tailwindcss/resolveConfig')。由于我的配置文件中有一些插件导入了 `fs`,所以我遇到了这个错误。所以我只是将纯配置数据和插件代码分开。现在我的 `tailwind.config.js` 导入并合并了两者(数据 + 插件),而 JS 应用程序只导入数据文件(不包含使用禁止依赖的插件)。

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