javascript - 如何修改 js 文件并使用 npm 命令保存?
问题描述
我有这个问题,我想用 npm 命令更改对象值(我使用 react)我把例子放在这里:
const GLOBAL_CONSTANTS = {
mobileIdNumber: '0',
FOOTER_TEXT_LOGIN: 'v.3.8.215',
DEFAULT_OFFSET: '-05:00',
MENU: {
ID_MODULE: 1,
},
};
export default GLOBAL_CONSTANTS;
我希望 FOOTER_TEXT_LOGIN 值更改为 v.3.8.216 或 +1,当我执行 npm run changeVersion 时,我已经尝试过使用 sh,但我不太清楚如何使用它。
解决方案
这种事情可以奏效。
const fs = require("fs");
// Pull the data from the file.
fs.readFile("./thing.json", 'utf-8', function (err, data) {
// Error handling (this isn't the only place in the code where errors
// can crop up, it's just the only place where I'm doing anything with
// them :P
if (err) {
return console.log(err);
}
// Since I decided to make the configuration file into json, I can
// read it with JSON.parse.
const parsed = JSON.parse(data);
// Split the version number from "0.1" to [0, 1].
const value = parsed.value.split('.');
// Coerce the second part of the value to a number and increment it.
// Typically you'd want to make sure that if the value could not be
// coerced, the process stops. I'll leave it up to you to implement
// that though.
value[1] = +value[1] + 1;
// Put the version number back together.
parsed.value = value.join('.');
// Replace the data in the file.
fs.writeFile("./thing.json", JSON.stringify(parsed), () => {});
});
如果您的配置是 json 格式,那就更容易了。否则,您必须对 javascript 代码进行字符串解析,但相同的基本概念有效。将数据拆开,找到要更改的值,更改它,然后将数据重新组合在一起。
这是我的代码更新的 json 文件(另存为 thing.json)。
{"value":"0.3"}
拥有脚本后,您可以通过在现有命令前加上或创建新命令来运行它node myscript.js
或将其包含在其中一个 package.json 脚本中。node myscript.js &&
推荐阅读
- c - How do I include libcurl in a custom local library to be used by local C applications
- python - websockets in micropython? (esp8266)
- javascript - 如何使用羽毛 js 更新 html 文档?
- python - What should I do if "except part" is not seen by python?
- python - Python 3.x:len(myList) 与 myList 的实际元素数不匹配
- android - 当应用程序完全关闭时向用户发送通知
- java - 从android(Java)中的另一个片段切换回来时恢复片段
- reactjs - 在 React.js 中,嵌套组件的生命周期方法是如何调用的?
- octave - 无法在八度音阶中设置刻度
- rust - 如何使用 gtk-rs 在列表存储/树视图中右对齐数字数据