You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过npm postbuild脚本实现跨操作系统的通用文件复制

Cross-Platform Solution for Copying Staticfile in Postbuild Script

You’re absolutely correct—your current copy Staticfile build command won’t work on macOS or Linux, since those operating systems use the cp command instead of Windows’ native copy. Here are two reliable, cross-platform ways to fix this issue:

There are npm packages built specifically to handle file operations across all OSes. copyfiles or cpy-cli are great choices because they abstract away system-specific command differences.

  1. Install the package
    Using npm:

    npm install copyfiles --save-dev
    

    Or using yarn:

    yarn add copyfiles --dev
    
  2. Update your package.json scripts
    Replace your existing copy script with one that uses copyfiles:

    "scripts": {
      "build": "react-scripts build",
      "postbuild": "npm run copy",
      "copy": "copyfiles -f Staticfile build"
    }
    

    The -f flag ensures the file is overwritten if it already exists in the build directory, preventing errors during subsequent builds.

Option 2: Use a Node.js Script (No Extra Dependencies)

If you prefer not to add another package, you can write a simple Node.js script using the built-in fs and path modules, which work consistently across Windows, macOS, and Linux.

  1. Create a new script file
    Make a file named copy-staticfile.js in your project root:

    const fs = require('fs');
    const path = require('path');
    
    // Define source and destination paths (handles cross-platform path separators)
    const sourcePath = path.join(__dirname, 'Staticfile');
    const destPath = path.join(__dirname, 'build', 'Staticfile');
    
    // Copy the file
    fs.copyFile(sourcePath, destPath, (error) => {
      if (error) {
        console.error('Error copying Staticfile:', error);
        process.exit(1); // Exit with error code if copy fails
      }
      console.log('Staticfile successfully copied to build directory!');
    });
    
  2. Update your package.json scripts
    Modify the postbuild command to run this Node.js script instead:

    "scripts": {
      "build": "react-scripts build",
      "postbuild": "node copy-staticfile.js"
    }
    

Both of these methods will ensure your Staticfile is copied to the build directory automatically, no matter which operating system you’re using. Just run yarn build (or npm run build) as usual, and the postbuild step will handle the copy seamlessly.

内容的提问来源于stack exchange,提问作者Pedro Accorsi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:52:34