如何通过npm postbuild脚本实现跨操作系统的通用文件复制
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:
Option 1: Use a Cross-Platform Copy Utility (Recommended)
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.
Install the package
Using npm:npm install copyfiles --save-devOr using yarn:
yarn add copyfiles --devUpdate your
package.jsonscripts
Replace your existingcopyscript with one that usescopyfiles:"scripts": { "build": "react-scripts build", "postbuild": "npm run copy", "copy": "copyfiles -f Staticfile build" }The
-fflag ensures the file is overwritten if it already exists in thebuilddirectory, 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.
Create a new script file
Make a file namedcopy-staticfile.jsin 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!'); });Update your
package.jsonscripts
Modify thepostbuildcommand 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

