简体   繁体   English

无法使用 webpack 解析“fs”并做出反应

[英]Can't resolve 'fs' using webpack and react

I keep getting the error in the description when I try to build my application for my Node server.当我尝试为我的 Node 服务器构建应用程序时,我不断收到描述中的错误。

I am ultimately trying to read a .docx file for docxtemplater, but without 'fs' working, it's not looking to bright.我最终试图读取 docxtemplater 的 .docx 文件,但没有 'fs' 工作,它看起来并不明亮。

I have tried to use the node:{fs:"empty"} workaround that I've seen on many solutions, but it's still giving me the same error or propagating up to the console when I am running it on the browser.我尝试使用 node:{fs:"empty"} 解决方法,我在许多解决方案中都看到过,但是当我在浏览器上运行它时,它仍然给我同样的错误或传播到控制台。

Here is what I have in my webpack.config.js:这是我在 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,
    }
};

You can't use any modules that come with the Node Core API in the browser, they just won't work there.您不能在浏览器中使用 Node Core API 附带的任何模块,它们在那里不起作用。 Node Core Modules rely on C/C++ binaries which won't be present in the browser.节点核心模块依赖于浏览器中不存在的 C/C++ 二进制文件。 So you'll need to find an equivalent approach to replacing any fs use in your react app.因此,您需要找到一种等效的方法来替换您的 React 应用程序中使用的任何fs

One approach would be to serve the file you want to work with over HTTP via a Node JS backend to your React app.一种方法是通过 Node JS 后端通过 HTTP 将要处理的文件提供给您的 React 应用程序。 You could read the file using fs in your Node server, and place that logic within a route, call that route from your React App via HTTP and stream it back.您可以在 Node 服务器中使用fs读取文件,并将该逻辑置于路由中,通过 HTTP 从 React App 调用该路由并将其流式传输回来。 Then you will have the file data within your React App and can work with it as you need.然后你将在你的 React 应用程序中拥有文件数据,并可以根据需要使用它。

This GitHub repo has a listing of Node Core Libraries that Webpack has ported over for browser usage.这个 GitHub 存储库列出了 Webpack 已移植以供浏览器使用的 Node 核心库。 Unfortunately fs isn't one of them.不幸的是fs不是其中之一。

Add in package.json在 package.json 中添加

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

Add in webpack:在 webpack 中添加:

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

I'm coming late, but this is docxtemplater specific.我来晚了,但这是特定于 docxtemplater 的。

To load a docx, you use fs in node, and JSZipUtils.getBinaryContent in the browser.要加载 docx,请在节点中使用fs ,在浏览器中使用JSZipUtils.getBinaryContent

See this demo (from here : http://docxtemplater.readthedocs.io/en/latest/generate.html#browser )看到这个演示(从这里: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM