简体   繁体   English

Webpack 开发服务器可以在我的项目根目录中创建文件吗?

[英]Can Webpack Dev server create files in my project root?

I have an project set up and running with Webpack 5.28.0 and webpack-dev-server 4.11.1我有一个项目设置和运行Webpack 5.28.0webpack-dev-server 4.11.1

Its all working nicely but I would like to be able to have the dev server write some files back to my project root.它一切正常,但我希望能够让开发服务器将一些文件写回我的项目根目录。 These are debug/log files that I'd like to save as JSON. I'd also like this to be automatic, I don't want to have to click anything or trigger the action manually.这些是我想保存为 JSON 的调试/日志文件。我也希望这是自动的,我不想点击任何东西或手动触发操作。

So the ideal flow would be that I run npm start , my build kicks off in a browser, the page generates a load of log data and this is then written back to my project root.所以理想的流程是我运行npm start ,我的构建在浏览器中启动,页面生成大量日志数据,然后将其写回我的项目根目录。 Either using some browser function or calling back to Node script in my build.使用某些浏览器 function 或在我的构建中回调到 Node 脚本。

Is this possible with dev-server?开发服务器可以吗?

You could setup the dev-server middleware to add an API endpoint to accept data and write it to your filesystem您可以设置开发服务器中间件以添加一个 API 端点以接受数据并将其写入您的文件系统

// webpack.config.js

const { writeFile } = require("node:fs/promises");
const bodyParser = require("body-parser");

module.exports = {
  // ...
  devServer: {
    setupMiddlewares: (middlewares, devServer) => {
      devServer.app?.post(
        "/__log",
        bodyParser.json(),
        async (req, res, next) => {
          try {
            await writeFile(
              "debug-log.json",
              JSON.stringify(req.body, null, 2)
            );
            res.sendStatus(202);
          } catch (err) {
            next(err);
          }
        }
      );
      return middlewares;
    },
  },
};

Then your front-end app needs only to construct the payload and POST it to the dev-server然后你的前端应用程序只需要构建有效负载并将其发布到开发服务器

const debugData = { /* ... */ };
fetch("/__log", {
  method: "POST",
  body: JSON.stringify(debugData),
  headers: { "content-type": "application/json" },
});

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

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