$PWD in npm script

Viewed 6349

Is there a way to concat $PWD with a string in package.json

I am trying:

"config": {
  "mypath" : "$(pwd)/assets/dist/js"
}

But it doesn't seem to work. Is it a way to access the current working path?

It works if I use it in a script. e.g.

"scripts": {
  "echo" : "echo $(pwd)/assets/dist/js"
}
2 Answers

Don't know your exact use-case, but you could use $npm_package_config_path in your script to pass it as an argument:

  "config" : {
    "path": "/assets/dist/js"
  },
  "scripts" : {
    "something":"CONFIG_PATH=${PWD}$npm_package_config_path node -e \"console.warn(process.env.CONFIG_PATH)\"",
  }
}

Then:

$> npm run something

/path/to/your/dir/assets/dist/js

I don't know where do You want to use config.mypath value but if you want to use this value in a script You could use this approach:

Before to start We have to know that: npm uses several programs to run the scripts. As default it uses bash in gnu/linux and cmd in windows (We can set the shell as in this question ). Therefore every script should be created to run over bash or cmd and often They are not compatibles.

Now let's get to work

  1. You could get config.mypath value as follows:

    "config": {
      "mypath" : "${PWD}/assets/dist/js"
    },
    "scripts": {
     "show-path": "echo $npm_package_config_mypath"
    }
    

    and run the command

    npm run show-path
    

    and the output would show us the config.path value

    ${PWD}/assets/dist/js
    

    of course this is not the value You want... but We can work with these value in a shell to get what We want.

  2. In bash We can use the next syntax to execute commands:

    echo [comand] |grep bash
    

    for example:

    echo echo \${PWD}/assets/dist/js | bash
    

    is the same as:

    echo ${PWD}/assets/dist/js
    

    and the output is:

    /home/user/assets/dist/js
    

    And I think these output is the value You want to read and use in your scripts...

  3. Now We can implement this trick to our package.json

    a) linux(bash):

     "config": {
       "mypath" : "${PWD}/git_repo"
     },
     "scripts": {
       "config": "echo  echo $npm_package_config_mypath  |bash",
       "git-clone":  "echo git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY ${npm_package_config_mypath}-foo | bash"
     }
    

    b) windows(cmd): in windows pwd works in powershell but in CMD pwd does not exist. Then we have to use %cd% and write our scripts with CMD syntax...

      "config": {
        "mypath": "%cd%\\git-repo"
      },
      "scripts": {
        "config": "echo echo %npm_package_config_mypath%  | cmd",
        "git-clone": "echo git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY %npm_package_config_mypath%-foo | cmd"
      }
    

In the examples config.mypath is used to create two scripts:

config: prints config.mypath value

git-clone: clones a repository in the config.mypath folder

Related