如何使用 npm 脚本获取 shell 脚本?

Jer*_*een 10 shell node.js npm nvm yarnpkg

我有一个脚本package.json

{
  "scripts": {
    "start": "source run-nvm.sh && ..."
  }
}
Run Code Online (Sandbox Code Playgroud)

但跑步source run-nvm.sh && ...yarn start(或npm run start)不同。

为什么?它创建了一个子shell。所以我不能改变原始 shell 的环境,我不能export为它常量或操纵它的状态nvm(我不能改变父 shell 的节点版本)

所以真正的问题

我可以通过不创建子shell来执行yarn/npm脚本吗?(并使用当前的外壳)

或者

如何使用 npm 脚本获取 shell 脚本?

最终,您可能会尝试通过询问以下问题来改变话语:“为什么不只是source run-nvm.sh && yarn start”但我不想只添加一些自定义脚本和复杂性,我希望它在yarn start/上自动执行npm start(自动更改节点版本)

真正的问题

它当前有效(脚本更改节点的版本并运行应用程序)但由于它是一个子shell,它不保存 nvm 的状态。因此,yarn start它最初使用默认版本,然后更改版本,然后启动应用程序,因此它yarn start为版本更改命令添加了约 3-4 秒。虽然它不应该每次都设置版本,但应该只设置一次,第一次。

Cha*_*tos 6

我今天遇到了这个问题,我找到了一个适合我的简单解决方案。

  1. 使用 vars 创建一个 env 文件

    # cat > .env << EOF
    PORT=8080
    DB_HOST=my-db.host
    DB_PORT=3306
    DB_USER=mysql
    DB_PASS=123456
    EOF
    
    Run Code Online (Sandbox Code Playgroud)
  2. package.json在文件上创建一个新条目

    {
      [...]
      "start": "export $(cat .env | egrep -v '#|^$' | xargs) && node production-server/server.js",
      [...]
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 像往常一样启动应用程序

    # npm run start
    
    > myapp@1.0.2 start /usr/local/myapp
    > export $(cat .env | egrep -v '#|^$' | xargs) && 
    node production-server/server.js
    
    > Ready on http://localhost:8080
    
    Run Code Online (Sandbox Code Playgroud)

就这样。

如果您想知道是什么export $(cat .env | egrep -v '#|^$' | xargs),请继续阅读。

export $(cat .env | egrep -v '#|^$' | xargs)
   |      |           |                 |
   |      |           |                 transform the output in "PORT=8080 DB_HOST=my-db.host DB_PORT=3306 DB_USER=mysql DB_PASS=123456"
   |      |           |
   |      |           filter lines starting with comment or blank line
   |      |
   |      cat the .env file
   |
   save the env on subshell before start the node
Run Code Online (Sandbox Code Playgroud)


Mic*_*itt 5

完全猜测,但尝试

{
 "scripts": {
    "start": "bash -c 'source run-nvm.sh && ...'"
  }
}
Run Code Online (Sandbox Code Playgroud)