【问题标题】:How to serve yarn build file with npm serve command?如何使用 npm serve 命令提供纱线构建文件?
【发布时间】:2020-01-22 06:25:05
【问题描述】:

基本上,我的任务是编译一个js文件并在http://localhost:5000/final.js提供它

我有以下脚本。

当前问题

  • console.log 似乎打印出了问题。
  • 可以切换目录并运行yarn build,但似乎无法提供文件

这里是源代码:

#!/usr/bin/env node

const frontendDir =
  "/my/frontend";
const jsDir =
  "/my/frontend/build/static/js";

// util
const util = require("util");
// exec
const exec = util.promisify(require("child_process").exec);

// async func
async function runcmd(cmd) {
  try {
    const { stdout, stderr } = await exec(cmd);
    // need output
    console.log("stdout:", stdout);
    // need error
    console.log("stderr:", stderr);
  } catch (err) {
    console.error(err);
  }
}

try {
  // go to front end dir
  process.chdir(frontendDir);
  console.log("Switch to dir: " + process.cwd());

  // yarn build
  runcmd("yarn build");

  // go to file dir
  process.chdir(jsDir);
  console.log("Switch to dir: " + process.cwd());

  // find that js file and copy it, rename it
  runcmd("cp main.*.js final.js");

  // serve at /my/frontend/build/static/js with url http://localhost:5000/final.js
  runcmd("serve .");
} catch (err) {
  console.log("chdir: " + err);
}

这是上面脚本的输出

Switch to dir: /my/frontend
Switch to dir: /my/frontend/build/static/js
stdout: 
stderr: 
stdout: yarn run v1.21.1
$ react-app-rewired build && cpr ./build/ ../build/frontend/ -o
Creating an optimized production build...
Compiled successfully.

File sizes after gzip:

  210.3 KB  build/static/js/main.c1e6b0e9.js

The project was built assuming it is hosted at ./.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.

Find out more about deployment here:



Done in 13.91s.

stderr:

【问题讨论】:

    标签: javascript node.js shell sh


    【解决方案1】:
    // https://stackoverflow.com/questions/41037042/nodejs-wait-for-exec-in-function
    const exec = require("child_process").exec;
    
    function os_func() {
      this.execCommand = function(cmd) {
        return new Promise((resolve, reject) => {
          exec(cmd, (error, stdout, stderr) => {
            if (error) {
              reject(error);
              return;
            }
            resolve(stdout);
          });
        });
      };
    }
    const os = new os_func();
    
    process.chdir(frontendDir);
    os.execCommand("yarn buildlocal")
      .then(() => {
        console.log("@ done yarn build");
        process.chdir(jsDir);
        os.execCommand("cp main.*.js docman.js").then(() => {
          console.log("@ done copy and serve at port 5000");
          os.execCommand("serve -l 5000 .").then(() => {});
        });
      })
      .catch(err => {
        console.log("os >>>", err);
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 2019-02-23
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      相关资源
      最近更新 更多