패키지를 사용하여 전역 및 로컬로 종속성을 설치합니다.제이손
을 사용하면 npm을 사용하여 할 수 .-g선택 에서 어떻게 요?패키지에서 어떻게 해야 합니까?json 파일?
이것들이 패키지에 있는 나의 종속성이라고 가정해 보겠습니다.json 파일
"dependencies": {
"mongoose": "1.4.0",
"node.io" : "0.3.3",
"jquery" : "1.5.1",
"jsdom" : "0.2.0",
"cron" : "0.1.2"
}
가 내가달때를 실행할 때.npm install는 오직 만나원요만 원합니다.node.io전체적으로 설치하려면 나머지는 로컬로 설치해야 합니다.이것에 대한 옵션이 있습니까?
새 노트:당신은 아마 이것을 원하지 않거나 할 필요가 없을 것입니다.빌드/테스트 등에 대한 명령 종속성 유형을 다음에 추가하는 것이 좋습니다.devDependencies당신의 패키지의 섹션.json.패키지에서 무언가를 사용할 때마다.devDependencies 명령(node_modules/.bin)의 j는 경로에 있는 것처럼 작동합니다.
예:
npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally
그럼 패키지로.json:
// devDependencies has mocha and babel now
"scripts": {
"test": "mocha",
"build": "babel -d lib src",
"prepublish": "babel -d lib src"
}
그런 다음 명령 프롬프트에서 다음을 실행할 수 있습니다.
npm run build # finds babel
npm test # finds mocha
npm publish # will run babel first
새 새 노트:한동안 우리는npx을 사용자의 devDependencies 할 수 .scripts섹션(원하는 경우).예:
npx webpack
그러나 전체적으로 설치하려는 경우 패키지의 스크립트 섹션에 사전 설치를 추가할 수 있습니다.json:
"scripts": {
"preinstall": "npm i -g themodule"
}
그래서 실제로 내 npm 설치는 npm 설치를 다시 실행합니다...이상하지만 효과가 있는 것 같습니다.
참고: 가장 일반적인 설정을 사용하는 경우 문제가 발생할 수 있습니다.npm는 필수 설치입니다.sudo은 당신의 한가옵는것다입니변경을 것입니다.npm구성할 필요가 없습니다.
npm config set prefix ~/npm$HOME을 $하려면 $/npm/bin을 $PATH에 export PATH=$HOME/npm/bin:$PATH의 신에게에.~/.bashrc.
또 다른, 아마도 더 나은 옵션은 그냥 사용하는 것입니다.nvm노드를 관리하면 문제가 발생하지 않습니다.
아래에 설명된 단점 때문에 수락된 답변을 따를 것을 권장합니다.
사용하다
npm install --save-dev [package_name]그런 다음 다음을 사용하여 스크립트를 실행합니다.$ npm run lint $ npm run build $ npm test
저의 원래의 추천되지 않은 답변은 다음과 같습니다.
설치를 를 로벌설치사는대패추를있다수니에 할 수 .devDependencies(--save-dev그런 다음 프로젝트 내부에서 바이너리를 실행합니다.
"$(npm bin)/<executable_name>" <arguments>...
당신의 경우:
"$(npm bin)"/node.io --help
이 엔지니어는 다음을 제공했습니다.npm-exec단축키로 별칭을 지정합니다.이 엔지니어는 다음과 같은 셸 스크립트를 사용합니다.env.sh하지만 나는 사용하는 것을 선호합니다.$(npm bin)파일이나 설정이 추가되지 않도록 직접 설정할 수 있습니다.
각 통화를 조금 더 크게 만들긴 하지만, 다음을 방지하기 위해 작동해야 합니다.
- 글로벌 패키지와 잠재적 종속성 충돌(@nally)
- 의 필요성
sudo - npm 접두사를 설정해야 합니다(어쨌든 하나를 사용하는 것이 좋습니다).
단점:
일반적인 작업(예: 빌드 및 축소)을 사용자의 "스크립트" 섹션에 배치하는 것이 더 나은 솔루션인 것 같습니다.package.json제이슨이 위에서 설명한 것처럼.
이것은 조금 오래된 것이지만, 제가 요구하는 사항에 부딪혔기 때문에 여기 제가 생각해 낸 해결책이 있습니다.
문제:
우리 개발팀은 많은 것을 유지하고 있습니다.Angular로 마이그레이션 중인 NET 웹 애플리케이션 제품JS/부트스트랩.VS2010은 커스텀 빌드 프로세스에 쉽게 적응하지 못하므로 개발자들은 정기적으로 여러 릴리스의 제품을 개발하고 있습니다.VCS는 하위 버전입니다(알고 있습니다).저는 Git로 옮기려고 하지만 제 성가신 마케팅 직원이 너무 까다로워요). 단일 VS 솔루션에는 여러 개의 개별 프로젝트가 포함될 것입니다.직원이 동일한 시스템에 동일한 노드 패키지(글프, 바우어 등)를 여러 번 설치하지 않고도 개발 환경을 초기화할 수 있는 공통적인 방법이 필요했습니다.
TL;DR:
글로벌 노드/타워 개발 환경과 로컬에서 필요한 모든 패키지를 설치하려면 "npm 설치"가 필요합니다.NET 제품.
글로벌 패키지는 아직 설치되지 않은 경우에만 설치해야 합니다.
글로벌 패키지에 대한 로컬 링크를 자동으로 만들어야 합니다.
솔루션:
우리는 이미 모든 개발자와 모든 제품이 공유하는 공통 개발 프레임워크를 가지고 있기 때문에 노드를 만들었습니다.필요할 때 글로벌 패키지를 설치하고 로컬 링크를 만드는 JS 스크립트.스크립트는 "..."에 있습니다.제품 기본 폴더와 관련된 \SharedFiles":
/*******************************************************************************
* $Id: npm-setup.js 12785 2016-01-29 16:34:49Z sthames $
* ==============================================================================
* Parameters: 'links' - Create links in local environment, optional.
*
* <p>NodeJS script to install common development environment packages in global
* environment. <c>packages</c> object contains list of packages to install.</p>
*
* <p>Including 'links' creates links in local environment to global packages.</p>
*
* <p><b>npm ls -g --json</b> command is run to provide the current list of
* global packages for comparison to required packages. Packages are installed
* only if not installed. If the package is installed but is not the required
* package version, the existing package is removed and the required package is
* installed.</p>.
*
* <p>When provided as a "preinstall" script in a "package.json" file, the "npm
* install" command calls this to verify global dependencies are installed.</p>
*******************************************************************************/
var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');
/*---------------------------------------------------------------*/
/* List of packages to install and 'from' value to pass to 'npm */
/* install'. Value must match the 'from' field in 'npm ls -json' */
/* so this script will recognize a package is already installed. */
/*---------------------------------------------------------------*/
var packages =
{
"bower" : "bower@1.7.2",
"event-stream" : "event-stream@3.3.2",
"gulp" : "gulp@3.9.0",
"gulp-angular-templatecache" : "gulp-angular-templatecache@1.8.0",
"gulp-clean" : "gulp-clean@0.3.1",
"gulp-concat" : "gulp-concat@2.6.0",
"gulp-debug" : "gulp-debug@2.1.2",
"gulp-filter" : "gulp-filter@3.0.1",
"gulp-grep-contents" : "gulp-grep-contents@0.0.1",
"gulp-if" : "gulp-if@2.0.0",
"gulp-inject" : "gulp-inject@3.0.0",
"gulp-minify-css" : "gulp-minify-css@1.2.3",
"gulp-minify-html" : "gulp-minify-html@1.0.5",
"gulp-minify-inline" : "gulp-minify-inline@0.1.1",
"gulp-ng-annotate" : "gulp-ng-annotate@1.1.0",
"gulp-processhtml" : "gulp-processhtml@1.1.0",
"gulp-rev" : "gulp-rev@6.0.1",
"gulp-rev-replace" : "gulp-rev-replace@0.4.3",
"gulp-uglify" : "gulp-uglify@1.5.1",
"gulp-useref" : "gulp-useref@3.0.4",
"gulp-util" : "gulp-util@3.0.7",
"lazypipe" : "lazypipe@1.0.1",
"q" : "q@1.4.1",
"through2" : "through2@2.0.0",
/*---------------------------------------------------------------*/
/* fork of 0.2.14 allows passing parameters to main-bower-files. */
/*---------------------------------------------------------------*/
"bower-main" : "git+https://github.com/Pyo25/bower-main.git"
}
/*******************************************************************************
* run */
/**
* Executes <c>cmd</c> in the shell and calls <c>cb</c> on success. Error aborts.
*
* Note: Error code -4082 is EBUSY error which is sometimes thrown by npm for
* reasons unknown. Possibly this is due to antivirus program scanning the file
* but it sometimes happens in cases where an antivirus program does not explain
* it. The error generally will not happen a second time so this method will call
* itself to try the command again if the EBUSY error occurs.
*
* @param cmd Command to execute.
* @param cb Method to call on success. Text returned from stdout is input.
*******************************************************************************/
var run = function(cmd, cb)
{
/*---------------------------------------------*/
/* Increase the maxBuffer to 10MB for commands */
/* with a lot of output. This is not necessary */
/* with spawn but it has other issues. */
/*---------------------------------------------*/
exec(cmd, { maxBuffer: 1000*1024 }, function(err, stdout)
{
if (!err) cb(stdout);
else if (err.code | 0 == -4082) run(cmd, cb);
else throw err;
});
};
/*******************************************************************************
* runCommand */
/**
* Logs the command and calls <c>run</c>.
*******************************************************************************/
var runCommand = function(cmd, cb)
{
console.log(cmd);
run(cmd, cb);
}
/*******************************************************************************
* Main line
*******************************************************************************/
var doLinks = (process.argv[2] || "").toLowerCase() == 'links';
var names = Object.keys(packages);
var name;
var installed;
var links;
/*------------------------------------------*/
/* Get the list of installed packages for */
/* version comparison and install packages. */
/*------------------------------------------*/
console.log('Configuring global Node environment...')
run('npm ls -g --json', function(stdout)
{
installed = JSON.parse(stdout).dependencies || {};
doWhile();
});
/*--------------------------------------------*/
/* Start of asynchronous package installation */
/* loop. Do until all packages installed. */
/*--------------------------------------------*/
var doWhile = function()
{
if (name = names.shift())
doWhile0();
}
var doWhile0 = function()
{
/*----------------------------------------------*/
/* Installed package specification comes from */
/* 'from' field of installed packages. Required */
/* specification comes from the packages list. */
/*----------------------------------------------*/
var current = (installed[name] || {}).from;
var required = packages[name];
/*---------------------------------------*/
/* Install the package if not installed. */
/*---------------------------------------*/
if (!current)
runCommand('npm install -g '+required, doWhile1);
/*------------------------------------*/
/* If the installed version does not */
/* match, uninstall and then install. */
/*------------------------------------*/
else if (current != required)
{
delete installed[name];
runCommand('npm remove -g '+name, function()
{
runCommand('npm remove '+name, doWhile0);
});
}
/*------------------------------------*/
/* Skip package if already installed. */
/*------------------------------------*/
else
doWhile1();
};
var doWhile1 = function()
{
/*-------------------------------------------------------*/
/* Create link to global package from local environment. */
/*-------------------------------------------------------*/
if (doLinks && !fs.existsSync(path.join('node_modules', name)))
runCommand('npm link '+name, doWhile);
else
doWhile();
};
이제 개발자를 위해 글로벌 도구를 업데이트하려면 "패키지" 개체를 업데이트하고 새 스크립트를 체크인합니다.개발자들은 이를 확인하고 "node npm-setup.js" 또는 글로벌 환경을 업데이트하기 위해 개발 중인 제품의 "npm install"로 실행합니다.전체 작업은 5분 걸립니다.
또한 새 개발자를 위한 환경을 구성하려면 먼저 NodeJS 및 GIT for Windows를 설치하고 컴퓨터를 재부팅한 후 "공유 파일" 폴더와 개발 중인 모든 제품을 체크아웃한 후 작업을 시작해야 합니다.
의 "package.json"입니다.NET 제품은 설치하기 전에 다음 스크립트를 호출합니다.
{
"name" : "Books",
"description" : "Node (npm) configuration for Books Database Web Application Tools",
"version" : "2.1.1",
"private" : true,
"scripts":
{
"preinstall" : "node ../../SharedFiles/npm-setup.js links",
"postinstall" : "bower install"
},
"dependencies": {}
}
메모들
스크립트 참조에는 윈도우즈 환경에서도 슬래시가 필요합니다.
"npmls"는 "package.json" "dependencies"에 나열되지 않았기 때문에 로컬로 연결된 모든 패키지에 대해 "npm ERR! extractive:" 메시지를 제공합니다.
1/29/16 편집
된 업트됨데.npm-setup.js과 같이 되었습니다.
패키지 은 "버전입니다.
var packages는 "이 "package" "package"로 되었습니다.npm install저장소가 할 수 되었습니다.등록된 리포지토리가 아닌 다른 곳에서 패키지를 설치할 수 있도록 변경되었습니다.패키지가 이미 설치되었지만 요청된 패키지가 아닌 경우 기존 패키지가 제거되고 올바른 패키지가 설치됩니다.
알 수 없는 이유로 npm은 설치 또는 링크를 수행할 때 주기적으로 EBUSY 오류(-4082)를 발생시킵니다.이 오류가 발생하여 명령이 다시 실행됩니다.오류가 두 번 발생하는 경우는 거의 없으며 항상 해결되는 것 같습니다.
다음과 같은 별도의 파일을 사용할 수 있습니다.npm_globals.txt에 package.json줄 바꿈으로써 줄에 포함시킬 것입니다.
mongoose@1.4.0
node.io@0.3.3
jquery@1.5.1
jsdom@0.2.0
cron@0.1.2
그런 다음 명령줄 실행에서
< npm_globals.txt xargs npm install -g
올바르게 설치되었는지 확인합니다.
npm list -g --depth=0
당신이 이것을 해야 할지 말아야 할지에 대해서는, 모두 사용 사례에 달려 있다고 생각합니다.대부분의 프로젝트에서는 이 작업이 필요하지 않으며, 프로젝트가 필요합니다.package.json이러한 도구와 종속성을 함께 캡슐화하는 것이 매우 선호됩니다.
에는 항상 를 하고 create-react-app그리고 다른 CLI는 새 시스템에 연결할 때 전체적으로 표시됩니다.버전 관리가 중요하지 않을 때 글로벌 도구와 그 종속성을 쉽게 설치할 수 있는 방법이 있으면 좋습니다.
그리고 요즘에는 전 세계적으로 패키지를 설치하는 대신 npm 패키지 러너를 사용하고 있습니다.
글로벌 종속성을 설치하기 위한 고유한 스크립트를 작성합니다.별로 필요 없어요. 패키지.json은 꽤 확장 가능합니다.
const { execSync } = require('child_process');
const fs = require('fs');
const package = JSON.parse(fs.readFileSync('package.json'));
let keys = Object.keys(package.dependencies);
let values = Object.values(package.dependencies);
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
let value = values[index].replace("~", "").replace("^", "");
console.log(`Installing: ${key}@${value} globally`,);
execSync('npm i -g ' + `${key}@${value}`);
}
위의 것들을 사용하면, 아래의 인라인으로도 만들 수 있습니다!
아래의 사전 설치를 확인하십시오.
{
"name": "Project Name",
"version": "0.1.0",
"description": "Project Description",
"main": "app.js",
"scripts": {
"preinstall": "node -e \"const {execSync} = require('child_process'); JSON.parse(fs.readFileSync('package.json')).globalDependencies.forEach(globaldep => execSync('npm i -g ' + globaldep));\"",
"build": "your transpile/compile script",
"start": "node app.js",
"test": "./node_modules/.bin/mocha --reporter spec",
"patch-release": "npm version patch && npm publish && git add . && git commit -m \"auto-commit\" && git push --follow-tags"
},
"dependencies": [
},
"globalDependencies": [
"cordova@8.1.2",
"ionic",
"potato"
],
"author": "author",
"license": "MIT",
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^5.2.0"
},
"bin": {
"app": "app.js"
}
}
노드 작성자는 패키지를 승인할 수 없습니다.json은 프로젝트 파일입니다.그러나 그것은 그렇다.
패키지의 모든 모듈.json은 ./node_sys/에 설치됩니다.
나는 이것이 명시적으로 명시된 것을 찾지 못했지만 이것이 패키지입니다.NPM에 대한 json 참조.
이것은 아마도 생산에 문제가 생길 수도 있습니다.프로젝트 종속성이 프로젝트 폴더 외부에 설치된 경우 다른 사용자가 패키지를 삭제 또는 교체하거나 폴더 권한을 변경하면 코드가 손상될 수 있습니다.
하나의 폴더에 모든 것을 저장하면 내구성이 향상되고 시스템을 예측할 수 있으며 유지보수 작업이 쉬워집니다.
언급URL : https://stackoverflow.com/questions/6480549/install-dependencies-globally-and-locally-using-package-json
'programing' 카테고리의 다른 글
| 대규모 마이그레이션:두 번째 외래 키가 phpMyAdmin에서 보조 키로 생성되지 않음 (0) | 2023.07.28 |
|---|---|
| 어떻게 멍해요?히스토그램: 작업? (0) | 2023.07.28 |
| python distutils 설치 방법 (0) | 2023.07.28 |
| MySQL 성능 - "IN" 절 vs.단일 값에 대해 동일(=) (0) | 2023.07.23 |
| sqlalchemy 필터여러 열 (0) | 2023.07.23 |