gpt4 book ai didi

node.js - npm postbuild 脚本在重命名文件时出现错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:22 27 4
gpt4 key购买 nike

我为 npm postbuild 制作了一个 Node 脚本,它执行简单的任务,在 react 应用程序中生成构建后重命名构建文件夹中的文件。

这是文件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:没有这样的文件或目录,重命名 C:\Users\HDL\Documents\demo-redux-app\build\static\js\*.js' -> 'C:\Users\HDL\Documents\demo-redux-app\build\static\js\bundle.js

即使文件和目录确实存在于构建目录中

构建目录的结构:

-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"
}
}

最佳答案

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);
}
...

关于node.js - npm postbuild 脚本在重命名文件时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51113514/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com