我为npm postbuild制作了一个节点脚本,该脚本执行简单的任务来在react应用程序生成生成文件后重命名build文件夹中的文件。
这是文件postbuild.js
let fs = require("fs");
let path = require("path");
const oldJSPath = path.join(__dirname, "build", "static", "js", "*.js");
const newJSPath = path.join(__dirname, "build", "static", "js", "bundle.js");
const oldCSSPath = path.join(__dirname, "build", "static", "css", "*.css");
const newCSSPath = path.join(__dirname, "build", "static", "css", "bundle.css");
fs.renameSync(oldJSPath, newJSPath);
fs.renameSync(oldCSSPath, newCSSPath);
现在的问题是我不断出错:
ENOENT: no such file or directory, rename C:\Users\HDL\Documents\demo-redux-app\build\static\js\*.js' -> 'C:\Users\HDL\Documents\demo-redux-app\build\static\js\bundle.js
即使文件和目录确实存在于构建目录中
build
目录的结构:
-build
-static
-css
*.css
-js
*.js
-media
*.png, jpg etc
不知道这是否必不可少,但这是package.json
:
{
"name": "demo-redux-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"react-scripts": "1.1.4",
"redux": "^4.0.0",
"redux-promise-middleware": "^5.1.1",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"postbuild": "node postbuild.js",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
答案 0 :(得分:1)
Node.js fs
不支持通配符。
如果要匹配*.js
中的第一个文件并将其重命名为bundle.js
,则可以使用glob来完成:
const globby = require('globby');
const newJSPath = path.join(__dirname, "build", "static", "js", "bundle.js");
const oldJSWildcardPath = path.join(__dirname, "build", "static", "js", "*.js");
const [oldJSPath] = globby.sync(oldJSWildcardPath);
if (oldJSPath) {
fs.renameSync(oldJSPath, newJSPath);
}
...
或使用正则表达式:
const newJSPath = path.join(__dirname, "build", "static", "js", "bundle.js");
const oldJSDirPath = path.join(__dirname, "build", "static", "js");
const [oldJSPath] = fs.readdirSync(oldJSDirPath).filter(filename => /.js$/.test(filename));
if (oldJSPath) {
fs.renameSync(oldJSPath, newJSPath);
}
...