gpt4 book ai didi

javascript - 无法使用传递给 "npm start"的参数配置 React Pre Hook

转载 作者:行者123 更新时间:2023-12-02 21:54:57 28 4
gpt4 key购买 nike

我创建了一个全新的项目:

$ npx create-react-app test-react-app && cd test-react-app && npm start

这里是仓库:https://github.com/tlg-265/test-react-app

我创建了一个新脚本:/prepare-project.js,其中包含以下内容:

let project = 'ferrari' // replace this value with the one passed via: $ npm start [what to put here?]

console.log(`########################`);
console.log(`###### The current project is: ${project} ######`);
console.log(`########################`);

文件:/package.json的内容是:

{
"name": "test-react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.3.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"prestart": "node prepare-project.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

您可以在其中看到我配置了预 Hook :

"prestart": "node prepare-project.js"

我的目标是运行:

$ npm start [what to put here?]

所以在脚本中:/prepare-project.js我可以读取该值。

我尝试过:

$ node prepare-project.js --project=mclaren

尝试从脚本内部读取该值时没有运气:prepare-project.js

知道如何实现这一目标吗?

谢谢!

最佳答案

您可以使用yargs模块来解析命令行参数,然后您可以使用child_process来执行您的命令。您的代码应如下所示,您可以添加自己的自定义逻辑。

const yargs = require('yargs');
const { execSync } = require('child_process');

const argv = yargs
.option('project', {
alias: 'p',
description: 'name of the project',
type: 'string',
})
.help()
.alias('help', 'h')
.argv;

console.log(argv.project);
console.log(`npm start --project=${argv.project}`);
const output = execSync(`npm start --project=${argv.project}`);
console.log(output)

关于javascript - 无法使用传递给 "npm start"的参数配置 React Pre Hook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60028029/

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