【问题标题】:Webpack : Cannot read property 'readFile' of undefined, No output filesWebpack:无法读取未定义的属性“readFile”,没有输出文件
【发布时间】:2021-08-02 08:58:51
【问题描述】:

使用webpack > 5 版本。下面是我的appDevMiddleware.jscongifuration

const path = require('path');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

function createWebpackMiddleware(compiler, publicPath) {
return webpackDevMiddleware(compiler, {
    // noInfo: true,
    publicPath,
    // silent: true,
    stats: 'errors-only',
});
}

module.exports = function addDevMiddlewares(app, webpackConfig) {
const compiler = webpack(webpackConfig);
const middleware = createWebpackMiddleware(compiler, webpackConfig.output.publicPath);

app.use(middleware);
app.use(webpackHotMiddleware(compiler));

// Since webpackDevMiddleware uses memory-fs internally to store build
// artifacts, we use it instead
const fs = middleware.fileSystem;

app.get('*', (req, res) => {
    fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
    if (err) {
        res.sendStatus(404);
    } else {
        res.send(file.toString());
    }
    });
});
};

当我对我的 React 应用程序执行 npm start 时,我得到了

TypeError: Cannot read property 'readFile' of undefined
at D:\master-instore-dashboard\server\middlewares\addDevMiddlewares.js:29:8

这正是在这里显示

fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {

我将不得不以某种方式将promises 用于readFile,类似于const { readFile } = require('fs').promises

对于这个问题,我应该如何用 promise 替换 const fs = middleware.fileSystem;

【问题讨论】:

    标签: javascript node.js reactjs webpack


    【解决方案1】:

    webpack-dev-middleware 使用memfs 作为其默认outputFileSystemWDM 没有公开API,因此您可以WDM 的实例中获取outputFileSystem。这就是你得到这个错误的原因。

    您应该创建自己的outputfilesystem,您可以使用memfs 明确地执行此操作。然后,您可以从内存文件系统中获取index.html

    您可以使用util Node.js 内置模块中的util.promisify() 方法来promisify fs.readFile 方法。

    例如

    webpack.config.js:

    const path = require("path");
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    
    module.exports = {
      entry: path.resolve(__dirname, "src/index.js"),
      output: {
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js",
      },
      plugins: [new HtmlWebpackPlugin({ template: "./src/index.html" })],
      mode: "development",
    };
    

    app.js:

    const path = require("path");
    const util = require("util");
    const express = require("express");
    const webpack = require("webpack");
    const webpackDevMiddleware = require("webpack-dev-middleware");
    const { createFsFromVolume, Volume } = require("memfs");
    const webpackConfig = require("./webpack.config");
    
    const compiler = webpack(webpackConfig);
    const app = express();
    const fs = createFsFromVolume(new Volume());
    fs.join = path.join.bind(path);
    const readFile = util.promisify(fs.readFile);
    
    const middleware = webpackDevMiddleware(compiler, {
      publicPath: webpackConfig.output.publicPath,
      stats: "errors-only",
      outputFileSystem: fs,
    });
    app.use(middleware);
    
    app.get("*", async (req, res) => {
      try {
        const file = await readFile(path.join(compiler.outputPath, "index.html"));
        res.send(file.toString());
      } catch (error) {
        res.sendStatus(404);
      }
    });
    
    app.listen(3000, () => console.log("Example app listening on port 3000!"));
    

    启动服务器:

    ⚡  node app.js                                                                                              
    Example app listening on port 3000!
    

    访问http://localhost:3000/test:

    ⚡  curl http://localhost:3000/test                                                <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    <script defer src="bundle.js"></script></head>
    
    <body>
    
    </body>
    
    </html>
    

    包版本:

    {
      "name": "68618902",
      "devDependencies": {
        "html-webpack-plugin": "^5.3.2",
        "memfs": "^3.2.2",
        "webpack": "^5.51.1",
        "webpack-dev-middleware": "^5.0.0"
      },
      "dependencies": {
        "express": "^4.17.1"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-05
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多