문제

어떻게 사용하의 로컬 버전에서 모듈 node.js.예를 들어,내 응용 프로그램을 설치,커피-스크립트:

npm install coffee-script

이에 그것을 설치 ./node_modules 커피 명령에 ./node_modules/.bin/coffee.는 방법이 있는 이 명령을 실행하면 저는 프로젝트의 주요 폴더?난 뭔가를 찾고 비슷 bundle exec 에 번들러.기본적으로,고 싶은 버전을 지정한 커피-스크립트는 프로젝트와 관련된 모든 사람에 사용해야 한다.

나도 추가 할 수 있습니다 -g 깃발을 설치하는 세계적으로 그래서 커피가 잘 어디에서든지만,무엇을 원하는 경우 다른 버전의 커피당 프로젝트가 있습니까?

도움이 되었습니까?

해결책

업데이트 : Seyeong Jeong이 아래에서 답변을 지적하므로 NPM 5.2.0은 npx [command]를 사용할 수 있으므로 더 편리합니다.

5.2.0 이전 버전의 이전 응답 :

에 문제가있는 문제
./node_modules/.bin
.

경로로 현재 작업 디렉토리가 프로젝트 디렉토리 구조의 루트 인 경우에만 작동한다는 것입니다 (즉, node_modules의 위치)

작업 디렉토리가 무엇인지,

로 로컬로 설치된 바이너리의 경로를 가져올 수 있습니다.
npm bin
.

프로젝트 디렉터리 계층 구조에있는 위치와 독립적으로 로컬로 설치된 coffee 바이너리를 실행하려면이 bash 구조를 사용할 수 있습니다

PATH=$(npm bin):$PATH coffee
.

i 님이 NPM-Exec

에 앨리어 링했습니다.
alias npm-exec='PATH=$(npm bin):$PATH'
.

그래서, 지금 나는 할 수있다

npm-exec coffee
.

어디에 있는지 상관없이 커피의 올바른 복사본을 실행합니다.

$ pwd
/Users/regular/project1

$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee

$ cd lib/
$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee

$ cd ~/project2
$ npm-exec which coffee
/Users/regular/project2/node_modules/.bin/coffee
.

다른 팁

Nice example

하지 않아 조작 $PATH 니다.

npm@5.2.0, npm 선박 npx 패키지 실행할 수 있는 명령어에서 지역 node_modules/.bin 거나 중앙에서 캐시입니다.

단순히 실행:

$ npx [options] <command>[@version] [command-arg]...

기본적으로, npx 여부를 확인합니다 <command> 에 존재하는 $PATH, 또는 로컬 프로젝트 바이너리,그리고 실행하는 것.

전화 npx <command><command> 에 없 $PATH 자동으로 설치 패키지와 함께 이름에서 NPM 레지스트리,당신을 위해 호출니다.그것이 끝나면,설치된 패키지지 않을 것 어느 곳에서 당신의 globals,그래서 당신 걱정할 필요가 없에 대해 오염에 오래-용어입니다.을 방지할 수 있습니다 이 행동에 의해 제공하는 --no-install 옵션입니다.

npm < 5.2.0, 설치할 수 있습니다 npx 패키지 수동으로 다음 명령을 실행하여:

$ npm install -g npx

npm bin 명령을 사용하여 프로젝트의 노드 모듈 / bin 디렉토리를 가져옵니다

$ $(npm bin)/<binary-name> [args]
.

e.g.

$ $(npm bin)/bower install
.

npm run[-script] <script name>

사용 후 고궁을 설치하는 빈 패키지는 귀하의 지역 ./node_modules directory,수정 package.json 를 추가 <script name> 다음과 같다:

$ npm install --save learnyounode
$ edit packages.json
>>> in packages.json
...
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "learnyounode": "learnyounode"
},
...
$ npm run learnyounode

면 그것은 좋은 것입니다 npm 설치했다--add-스크립트 옵션 또는 무언가를 경우 또는 npm 실행 작동 추가하지 않고 스크립트를 차단합니다.

npm-run .

readme에서 :

npm-run

node_modules에서 로컬 실행 파일 찾기 및 실행

NPM 수명주기 스크립트에서 사용할 수있는 실행 파일은 npm-run에서 사용할 수 있습니다.

사용량

$ npm install mocha # mocha installed in ./node_modules
$ npm-run mocha test/* # uses locally installed mocha executable 
.

설치

$ npm install -g npm-run
.

update : 언급 된 보안상의 이유로 더 이상이 메소드를 권장하지 않으며 최신 npm bin 명령은 모두 권장하지 않습니다.원래 답변 :

알아 낸 것처럼 현지 설치된 바이너리는 ./node_modules/.bin에 있습니다.항상 전 세계적으로 사용 가능한 바이너리가 아닌이 디렉토리에서 항상 바이너리를 실행하려면 PANTACODETAGCODE를 먼저 PATH에 넣는 것이 좋습니다.

export PATH="./node_modules/.bin:$PATH"
.

./node_modules/.bin에 넣으면 ~/.profile가 사용 가능한 경우 coffee입니다. 그렇지 않으면 ./node_modules/.bin/coffee (또는 노드 모듈을 설치하는 모든 접두사)를 사용하십시오.

경로 솔루션은 $ (NPM BIN)이 .profile / .bashrc / etc에 배치 된 경우 한 번 평가되며 경로가 처음으로 평가 된 디렉토리에 영원히 설정됩니다. 대신에현재 경로는 스크립트를 실행할 때마다 경로가 커집니다.

이러한 문제를 해결하려면 기능을 만들고 사용됩니다.환경을 수정하지 않으며 사용하기 쉽습니다.

function npm-exec {
   $(npm bin)/$@  
}
.

이는 환경을 변경하지 않고이와 같이 사용할 수 있습니다.

npm-exec r.js <args>
.

NPM을 유지하려면 NPX 가 필요로하는 것을해야합니다.


원사로 전환하면 (페이스 북에 의한 NPM 교체) 옵션이면 다음을 호출 할 수 있습니다.

 yarn yourCmd
. 스크립트가 없으면 ./node_modules/.bin/ 폴더를 찾을 수없는 경우 우선 순위가 있습니다.

그것은 또한 실행 된 것을 출력합니다 :

$ yarn tsc
yarn tsc v0.27.5
$ "/home/philipp/rate-pipeline/node_modules/.bin/tsc"
.

package.json에서 각 명령에 대한 스크립트를 설정할 필요가 없습니다.


.scripts 내부의 package.json에서 정의 된 스크립트가있는 경우 :

"tsc": "tsc" // each command defined in the scripts will be executed from `./node_modules/.bin/` first
.

yarn tscyarn run tsc 또는 npm run tsc와 동일합니다.

 yarn tsc
 yarn tsc v0.27.5
 $ tsc
.

업데이트 : 최근 NPM (버전> 5.2) 다음을 사용할 수 있습니다 :

npx <command>
.

npx .bin

node_modules 디렉토리에서 명령을 찾습니다.

오래된 답변 :

Windows

npm-exec.bat라는 파일에 다음을 저장하고 %PATH%

에 추가하십시오.
@echo off
set cmd="npm bin"
FOR /F "tokens=*" %%i IN (' %cmd% ') DO SET modules=%%i
"%modules%"\%*
.

사용량

다음을 사용할 수 있습니다 npm-exec <command> <arg0> <arg1> ...

예를 들어

로컬 node_modules 디렉토리에 설치된 wdio를 실행하려면 다음을 수행하십시오.

npm-exec wdio wdio.conf.js
.

i.e..\node_modules\.bin\wdio wdio.conf.js

를 실행합니다

I prefer to not rely on shell aliases or another package.

Adding a simple line to scripts section of your package.json, you can run local npm commands like

npm run webpack

package.json

{
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack"
  },
  "devDependencies": {
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.11"
  }
}

If you want your PATH variable to correctly update based on your current working directory, add this to the end of your .bashrc-equivalent (or after anything that defines PATH):

__OLD_PATH=$PATH
function updatePATHForNPM() {
  export PATH=$(npm bin):$__OLD_PATH
}

function node-mode() {
  PROMPT_COMMAND=updatePATHForNPM
}

function node-mode-off() {
  unset PROMPT_COMMAND
  PATH=$__OLD_PATH
}

# Uncomment to enable node-mode by default:
# node-mode

This may add a short delay every time the bash prompt gets rendered (depending on the size of your project, most likely), so it's disabled by default.

You can enable and disable it within your terminal by running node-mode and node-mode-off, respectively.

I've always used the same approach as @guneysus to solve this problem, which is creating a script in the package.json file and use it running npm run script-name.

However, in the recent months I've been using npx and I love it.

For example, I downloaded an Angular project and I didn't want to install the Angular CLI globally. So, with npx installed, instead of using the global angular cli command (if I had installed it) like this:

ng serve

I can do this from the console:

npx ng serve

Here's an article I wrote about NPX and that goes deeper into it.

zxc is like "bundle exec" for nodejs. It is similar to using PATH=$(npm bin):$PATH:

$ npm install -g zxc
$ npm install gulp
$ zxc which gulp
/home/nathan/code/project1/node_modules/.bin/gulp

Same @regular 's accepted solution, but Fish shell flavour

if not contains (npm bin) $PATH
    set PATH (npm bin) $PATH
end

You can also use direnv and change the $PATH variable only in your working folder.

$ cat .envrc
> export PATH=$(npm bin):$PATH

Add this script to your .bashrc. Then you can call coffee or anyhting locally. This is handy for your laptop, but don't use it on your server.

DEFAULT_PATH=$PATH;

add_local_node_modules_to_path(){
  NODE_MODULES='./node_modules/.bin';
  if [ -d $NODE_MODULES ]; then
    PATH=$DEFAULT_PATH:$NODE_MODULES;
  else
    PATH=$DEFAULT_PATH;
  fi
}

cd () {
  builtin cd "$@";
  add_local_node_modules_to_path;
}

add_local_node_modules_to_path;

note: this script makes aliase of cd command, and after each call of cd it checks node_modules/.bin and add it to your $PATH.

note2: you can change the third line to NODE_MODULES=$(npm bin);. But that would make cd command too slow.

For Windows use this:

/* cmd into "node_modules" folder */
"%CD%\.bin\grunt" --version

I encountered the same problem and I don't particularly like using aliases (as regular's suggested), and if you don't like them too then here's another workaround that I use, you first have to create a tiny executable bash script, say setenv.sh:

#!/bin/sh

# Add your local node_modules bin to the path
export PATH="$(npm bin):$PATH"

# execute the rest of the command
exec "$@"

and then you can then use any executables in your local /bin using this command:

./setenv.sh <command>
./setenv.sh 6to5-node server.js
./setenv.sh grunt

If you're using scripts in package.json then:

...,
scripts: {
    'start': './setenv.sh <command>'
}

I'd love to know if this is an insecure/bad idea, but after thinking about it a bit I don't see an issue here:

Modifying Linus's insecure solution to add it to the end, using npm bin to find the directory, and making the script only call npm bin when a package.json is present in a parent (for speed), this is what I came up with for zsh:

find-up () {
  path=$(pwd)
  while [[ "$path" != "" && ! -e "$path/$1" ]]; do
    path=${path%/*}
  done
  echo "$path"
}

precmd() {
  if [ "$(find-up package.json)" != "" ]; then
    new_bin=$(npm bin)
    if [ "$NODE_MODULES_PATH" != "$new_bin" ]; then
      export PATH=${PATH%:$NODE_MODULES_PATH}:$new_bin
      export NODE_MODULES_PATH=$new_bin
    fi
  else
    if [ "$NODE_MODULES_PATH" != "" ]; then
      export PATH=${PATH%:$NODE_MODULES_PATH}
      export NODE_MODULES_PATH=""
    fi
  fi
}

For bash, instead of using the precmd hook, you can use the $PROMPT_COMMAND variable (I haven't tested this but you get the idea):

__add-node-to-path() {
  if [ "$(find-up package.json)" != "" ]; then
    new_bin=$(npm bin)
    if [ "$NODE_MODULES_PATH" != "$new_bin" ]; then
      export PATH=${PATH%:$NODE_MODULES_PATH}:$new_bin
      export NODE_MODULES_PATH=$new_bin
    fi
  else
    if [ "$NODE_MODULES_PATH" != "" ]; then
      export PATH=${PATH%:$NODE_MODULES_PATH}
      export NODE_MODULES_PATH=""
    fi
  fi   
}

export PROMPT_COMMAND="__add-node-to-path"

I am a Windows user and this is what worked for me:

// First set some variable - i.e. replace is with "xo"
D:\project\root> set xo="./node_modules/.bin/"

// Next, work with it
D:\project\root> %xo%/bower install

Good Luck.

In case you are using fish shell and do not want to add to $path for security reason. We can add the below function to run local node executables.

### run executables in node_module/.bin directory
function n 
  set -l npmbin (npm bin)   
  set -l argvCount (count $argv)
  switch $argvCount
    case 0
      echo please specify the local node executable as 1st argument
    case 1
      # for one argument, we can eval directly 
      eval $npmbin/$argv
    case '*'
      set --local executable $argv[1]
      # for 2 or more arguments we cannot append directly after the $npmbin/ since the fish will apply each array element after the the start string: $npmbin/arg1 $npmbin/arg2... 
      # This is just how fish interoperate array. 
      set --erase argv[1]
      eval $npmbin/$executable $argv 
  end
end

Now you can run thing like:

n coffee

or more arguments like:

n browser-sync --version

Note, if you are bash user, then @Bob9630 answers is the way to go by leveraging bash's $@, which is not available in fishshell.

Include coffee-script in package.json with the specific version required in each project, typically like this:

"dependencies":{
  "coffee-script": ">= 1.2.0"

Then run npm install to install dependencies in each project. This will install the specified version of coffee-script which will be accessible locally to each project.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top