首页 > 解决方案 > 如何修改 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,但我不太清楚如何使用它。

标签: javascriptnode.js

解决方案


这种事情可以奏效。

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 &&


推荐阅读