Npmrc где лежит
Перейти к содержимому

Npmrc где лежит

  • автор:

Where is NPM config file?

I edited the npm config file with npm edit config . I made a syntax error in it and saved the file. Now, no matter what I try with npm, it will complain about it. I know what the syntax is and I would like to fix it, but I can’t find the file anywhere.

C:\Users\Arthur>npm Error: Failed parsing JSON config key cache: "C:\Users\Le Roi Arthur\AppData\Roaming\npm-cache" at parseField (D:\nodejs\node_modules\npm\lib\config\core.js:376:13) at D:\nodejs\node_modules\npm\lib\config\core.js:330:24 at Array.forEach () at Conf.add (D:\nodejs\node_modules\npm\lib\config\core.js:328:23) at ConfigChain.addString (D:\nodejs\node_modules\npm\node_modules\config-chain\index.js:244:8) at Conf. (D:\nodejs\node_modules\npm\lib\config\core.js:316:10) at D:\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:90:16 at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3) TypeError: Cannot read property 'loaded' of undefined at exit (D:\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27) at errorHandler (D:\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3) at D:\nodejs\node_modules\npm\bin\npm-cli.js:77:20 at cb (D:\nodejs\node_modules\npm\lib\npm.js:225:22) at D:\nodejs\node_modules\npm\lib\npm.js:263:24 at D:\nodejs\node_modules\npm\lib\config\core.js:83:7 at Array.forEach () at Conf. (D:\nodejs\node_modules\npm\lib\config\core.js:82:13) at Conf.f (D:\nodejs\node_modules\npm\node_modules\once\once.js:25:25) at Object.onceWrapper (events.js:286:20) D:\nodejs\node_modules\npm\lib\utils\error-handler.js:98 var doExit = npm.config.loaded ? npm.config.get('_exit') : true ^ TypeError: Cannot read property 'loaded' of undefined at exit (D:\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27) at process.errorHandler (D:\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3) at process.emit (events.js:198:13) at process._fatalException (internal/bootstrap/node.js:496:27) Error: Failed parsing JSON config key cache: "C:\Users\Le Roi Arthur\AppData\Roaming\npm-cache" at parseField (D:\nodejs\node_modules\npm\lib\config\core.js:376:13) at D:\nodejs\node_modules\npm\lib\config\core.js:330:24 at Array.forEach () at Conf.add (D:\nodejs\node_modules\npm\lib\config\core.js:328:23) at ConfigChain.addString (D:\nodejs\node_modules\npm\node_modules\config-chain\index.js:244:8) at Conf. (D:\nodejs\node_modules\npm\lib\config\core.js:316:10) at D:\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:90:16 at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3) TypeError: Cannot read property 'loaded' of undefined at exit (D:\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27) at errorHandler (D:\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3) at D:\nodejs\node_modules\npm\bin\npm-cli.js:77:20 at cb (D:\nodejs\node_modules\npm\lib\npm.js:225:22) at D:\nodejs\node_modules\npm\lib\npm.js:263:24 at D:\nodejs\node_modules\npm\lib\config\core.js:83:7 at Array.forEach () at Conf. (D:\nodejs\node_modules\npm\lib\config\core.js:82:13) at Conf.f (D:\nodejs\node_modules\npm\node_modules\once\once.js:25:25) at Object.onceWrapper (events.js:286:20) D:\nodejs\node_modules\npm\lib\utils\error-handler.js:98 var doExit = npm.config.loaded ? npm.config.get('_exit') : true ^ TypeError: Cannot read property 'loaded' of undefined at exit (D:\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27) at process.errorHandler (D:\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3) at process.emit (events.js:198:13) at process._fatalException (internal/bootstrap/node.js:496:27) 

Uninstalling and re-installing nodeJS doesn’t fix the issue, the file is stored in cache somewhere. It’s infuriately frustrating how hard it is to put my hands on that file. Where can I find the npm config file ?

Configure Babel

Babel can be configured! Many other tools have similar configs: ESLint ( .eslintrc ), Prettier ( .prettierrc ).

All Babel API options are allowed. However, if the option requires JavaScript, you may want to use a JavaScript configuration file.

What’s your use case?​

  • You are using a monorepo?
  • You want to compile node_modules ?
  • You have a configuration that only applies to a single part of your project?
  • Guy Fieri is your hero?

babel.config.json ​

Create a file called babel.config.json with the following content at the root of your project (where the package.json is).

babel.config.json

  "presets": [. ], "plugins": [. ] > 

Check out the babel.config.json documentation to see more configuration options.

.babelrc.json ​

Create a file called .babelrc.json with the following content in your project.

.babelrc.json

  "presets": [. ], "plugins": [. ] > 

Check out the .babelrc documentation to see more configuration options.

package.json ​

Alternatively, you can choose to specify your .babelrc.json config from within package.json using the babel key like so:

package.json

  "name": "my-package", "version": "1.0.0", "babel":   "presets": [ . ], "plugins": [ . ], > > 

JavaScript configuration files​

You can also write babel.config.js (like we’re doing), and .babelrc.js files using JavaScript:

babel.config.js

module.exports = function (api)   api.cache(true);  const presets = [ . ]; const plugins = [ . ];  return   presets,  plugins >; > 

You are allowed to access any Node.js APIs, for example a dynamic configuration based on the process environment:

babel.config.js

module.exports = function (api)   api.cache(true);  const presets = [ . ]; const plugins = [ . ];  if (process.env["ENV"] === "prod")   plugins.push(. ); >  return   presets,  plugins >; > 

You can read more about JavaScript configuration files in the dedicated documentation

Using the CLI ( @babel/cli )​

babel --plugins @babel/plugin-transform-arrow-functions script.js 

Check out the babel-cli documentation to see more configuration options.

Using the API ( @babel/core )​

JavaScript

require("@babel/core").transformSync("code",   plugins: ["@babel/plugin-transform-arrow-functions"], >); 

Check out the babel-core documentation to see more configuration options.

Print effective configs​

You can tell Babel to print effective configs on a given input path

  • Shell
  • powershell
  # *nix or WSL BABEL_SHOW_CONFIG_FOR=./src/myComponent.jsx npm start 
  $env:BABEL_SHOW_CONFIG_FOR = ".srcmyComponent.jsx"; npm start 

BABEL_SHOW_CONFIG_FOR accepts both absolute and relative file paths. If it is a relative path, it will be resolved from cwd .

Once Babel processes the input file specified by BABEL_SHOW_CONFIG_FOR , Babel will print effective configs to the console. Here is an example output:

Babel configs on "/path/to/cwd/src/index.js" (ascending priority): config /path/to/cwd/babel.config.json   "sourceType": "script",  "plugins": [  "@foo/babel-plugin-1"  ],  "extends": "./my-extended.js" > config /path/to/cwd/babel.config.json .env["test"]   "plugins": [  [  "@foo/babel-plugin-3",    "noDocumentAll": true  >,  ]  ] > config /path/to/cwd/babel.config.json .overrides[0]   "test": "src/index.js",  "sourceMaps": true > config /path/to/cwd/.babelrc <> programmatic options from @babel/cli   "sourceFileName": "./src/index.js",  "presets": [  "@babel/preset-env"  ],  "configFile": "./my-config.js",  "caller":  "name": "@babel/cli"  >,  "filename": "./src/index.js" > 

Babel will print effective config sources ordered by ascending priority. Using the example above, the priority is:

babel.config.json < .babelrc < programmatic options from @babel/cli

In other words, babel.config.json is overwritten by .babelrc , and .babelrc is overwritten by programmatic options.

For each config source, Babel prints applicable config items (e.g. overrides and env ) in the order of ascending priority. Generally each config sources has at least one config item — the root content of configs. If you have configured overrides or env , Babel will not print them in the root, but will instead output a separate config item titled as .overrides[index] , where index is the position of the item. This helps determine whether the item is effective on the input and which configs it will override.

If your input is ignored by ignore or only , Babel will print that this file is ignored.

How Babel merges config items​

Babel’s configuration merging is relatively straightforward. Options will overwrite existing options when they are present and their value is not undefined . There are, however, a few special cases:

  • For assumptions , parserOpts and generatorOpts , objects are merged, rather than replaced.
  • For plugins and presets , they are replaced based on the identity of the plugin/preset object/function itself combined with the name of the entry.
Option (except plugin/preset) merging​

As an example, consider a config with:

JavaScript

  sourceType: "script", assumptions:   setClassFields: true, iterableIsArray: false >, env:   test:   sourceType: "module", assumptions:   iterableIsArray: true, >, > > >; 

When NODE_ENV is test , the sourceType option will be replaced and the assumptions option will be merged. The effective config is:

JavaScript

  sourceType: "module", // sourceType: "script" is overwritten assumptions:   setClassFields: true, iterableIsArray: true, // assumptions are merged by Object.assign >, > 
Plugin/Preset merging​

As an example, consider a config with:

JavaScript

plugins: [ './other', ['./plug',  thing: true, field1: true >] ], overrides: [  plugins: [ ['./plug',  thing: false, field2: true >], ] >] 

The overrides item will be merged on top of the top-level options. Importantly, the plugins array as a whole doesn’t just replace the top-level one. The merging logic will see that «./plug» is the same plugin in both cases, and < thing: false, field2: true >will replace the original options, resulting in a config as

JavaScript

plugins: [ './other', ['./plug',  thing: false, field2: true >], ], 

Since merging is based on identity + name, it is considered an error to use the same plugin with the same name twice in the same plugins / presets array. For example

JavaScript

plugins: ["./plug", "./plug"]; 

is considered an error, because it’s identical to plugins: [‘./plug’] . Additionally, even

JavaScript

plugins: [["./plug",  one: true >], ["./plug",  two: true >]]; 

is considered an error, because the second one would just always replace the first one.

If you actually do want to instantiate two separate instances of a plugin, you must assign each one a name to disambiguate them. For example:

JavaScript

plugins: [ ["./plug",  one: true >, "first-instance-name"], ["./plug",  two: true >, "second-instance-name"], ]; 

because each instance has been given a unique name and thus a unique identity.

Saved searches

Use saved searches to filter your results more quickly

Cancel Create saved search

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

yarnpkg / yarn Public

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Where is the global yarn config file? #3010

binarykitchen opened this issue Mar 29, 2017 · 11 comments

Where is the global yarn config file? #3010

binarykitchen opened this issue Mar 29, 2017 · 11 comments

Comments

Contributor
binarykitchen commented Mar 29, 2017

Searched for this information everywhere but can’t find any clues. Like the .npmrc I want to back it up in case of a data loss and/or sync it to other machines.

Something like yarn config where or so would be cool.

The text was updated successfully, but these errors were encountered:

arcanis closed this as completed Mar 29, 2017
Contributor Author
binarykitchen commented Mar 30, 2017

. but why am i seeing lastUpdateCheck there? this prevents me from syncing the yarn config file among all my machines 🙁

i think the yarn config contents should be independent from the local state. save local state elsewhere like you do with lock files. reopen or raise this as a new issue?

arcanis commented Mar 30, 2017

You can actually move your yarnrc file into your project folder, and it will still work (that’s useful for a number of use cases, such as offline mirrors). We probably can’t make it the default behaviour tho, both for backward compatibility reasons, and because it makes sense for some other configuration values to be stored in a «global» yarnrc file.

Contributor Author
binarykitchen commented Mar 31, 2017

sure, sounds good — but lastUpdateCheck? it is a local state. imagine you add it to your project folder, push that to a git repo and someone else pulls it? lastUpdateCheck won’t be correct on the puller’s machine. hence i am hesitant to sync that global yarnrc file among all my machines .

UnwashedMeme commented May 16, 2017

let prefix = path . dirname ( path . dirname ( process . execPath ) ) ;

that it looks at the node executable and calculates a prefix relative to that; it will then look in that prefix for a .yarnrc file. so in the docker library node:6 image I was able to make /usr/local/.yarnrc and actually set config globally.

Don’t like it, but it works until yarn respects either the -g flag (#1037) or /usr/local/etc/yarnrc or something.

jylin commented Jun 25, 2017

Per what @binarykitchen was saying, the «~/.yarnrc» should not contain local state or things like «# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.». RC files should be stateless files describing user configuration. In it’s current state, you can’t really add it to your dotfiles repo.

bronson mentioned this issue Aug 9, 2017
bronson commented Aug 9, 2017

I just got tripped up by this so I tried to express @binarykitchen’s point in a new issue: #4134

liudonghua123 commented Dec 11, 2019

// npmrc —> ./.npmrc, ~/.npmrc, $/etc/npmrc

Contributor
x-yuri commented Sep 19, 2020 •

First, you can make yarn verbose:

$ yarn config list --verbose yarn config v1.22.5 verbose 0.597431427 Checking for configuration file "/home/yuri/src/yarn/.npmrc". verbose 0.59781497 Checking for configuration file "/home/yuri/.npmrc". verbose 0.597974459 Checking for configuration file "/usr/etc/npmrc". verbose 0.598141219 Checking for configuration file "/home/yuri/src/yarn/.npmrc". verbose 0.598267605 Checking for configuration file "/home/yuri/src/.npmrc". verbose 0.598411356 Checking for configuration file "/home/yuri/.npmrc". verbose 0.59856281 Checking for configuration file "/home/.npmrc". verbose 0.599382032 Checking for configuration file "/home/yuri/src/yarn/.yarnrc". verbose 0.599593107 Checking for configuration file "/home/yuri/.yarnrc". verbose 0.599742477 Found configuration file "/home/yuri/.yarnrc". verbose 0.600010627 Checking for configuration file "/usr/etc/yarnrc". verbose 0.600149379 Checking for configuration file "/home/yuri/src/yarn/.yarnrc". verbose 0.600264049 Checking for configuration file "/home/yuri/src/.yarnrc". verbose 0.600378495 Checking for configuration file "/home/yuri/.yarnrc". verbose 0.600490923 Found configuration file "/home/yuri/.yarnrc". verbose 0.600689103 Checking for configuration file "/home/.yarnrc". . 

Second, if you’re root (inside docker ?), for yarn your home ( userHome ) is at /usr/local/share .

Third, $prefix is either $/usr/local , or $userHome/.yarn (the first that contains a bin dir). Do note that root’s home is at /usr/local/share , not $prefix/share .

Fourth, the function that does the checking is getPossibleConfigLocations() . So basically it checks in:

./.yarnrc ~/.yarnrc or /usr/local/share/.yarnrc $prefix/etc/yarnrc ../.yarnrc ../../.yarnrc . 

this.enableDefaultRc is true by default, but you can make it false ( —no-default-rc ). this.extraneousRcFiles is populated by passing —use-yarnrc .myyarnrc (possibly multiple times).

yarn config set makes changes to the home config ( $userHome/.yarnrc ).

Две малоизвестные, но полезные команды npm

Команды npm list (npm ls) и npm config list (npm config ls) не особо популярны. Тем не менее они помогут решить некоторые проблемы в среде разработки, избавив от “ловушек” и “тупиков”.

1. npm list/ls

Менеджер npm включает в себя тысячи пакетов. Многие из них обычно используют другие пакеты в качестве зависимостей. А те, в свою очередь, нуждаются в других пакетах в качестве зависимостей.

Бывает так, что глубине этих зависимостей не видно конца. Но иногда нужно найти имя конкретного пакета, который используется в проекте. В этом поможет команда npm list. Продемонстрируем ее действие на примере:

Вот так может выглядеть дерево зависимостей. В данном проекте было сгенерировано более 900 строк в виде дерева, а здесь представлен обрезанный скриншот.

Иногда трудно найти конкретное имя проекта в окне терминала. Вы можете экспортировать его в файл следующим образом: npm list > dependencyList.txt.

Несколько полезных конфигураций для npm list

Иногда нужно найти пакеты глобально установленные/первого уровня. В этом случае поможет конфигурация — depth=0 :

Кроме того, если необходим другой уровень глубины, можно настроить его следующим образом: — depth=1, 2, 3, … .

Вывод древовидного представления npm list, имеющий своеобразный синтаксис, иногда может сбивать с толку. Если вы испытываете трудности, используйте конфигурацию — json для создания вывода в формате json:

2. npm config list/ls

Если вы работаете в крупной компании или у вашей организации есть частный реестр пакетов npm, то вы, вероятно, периодически используете публичный (registry.npmjs.org) и частный реестры.

Npm использует файл .npmrc для управления регистрацией. Например, чтобы переключить реестр на приватный сервер реестра компании, нужно написать адрес сервера реестра в файле .npmrc следующим образом:

Это означает, что npm будет использовать этот сервер в качестве адреса реестра каждый раз, пока вы не измените его.

Однако с файлом .npmrc могут возникнуть некоторые проблемы. Дело в том, что он представлен не в единственном числе. Обычно он находится в папке user (для Windows) на диске компьютера, но может оказаться в нескольких других местах (например, в папке проекта). Более того, место, в котором осуществляется запуск команды npm (например, npm install ), имеет решающее значение для определения того, какой реестр будет использоваться npm в этой команде.

Допустим, у вас два файла .npmrc. Один из них находится в папке пользователя как registry=http://first-registry-server/ , другой — в папке проекта как r egistry=http://second-registry-server/ . Вы хотите запустить команду npm install . Если запустить ее в папке проекта, npm установит пакеты с second-registry-server . Если же запустить ее вне расположения проекта, npm установит пакеты с first-registry-server .

Вам может казаться, что вы справитесь с этим. Но иногда просто невозможно понять, почему npm не находит пакеты. Пытаясь всячески разрулить ситуацию, вы рискуете упустить главный источник проблемы. Поэтому в такие моменты лучше использовать команду npm config list . Она предоставит дамп о ваших конфигурациях npm. Там же вы увидите информацию о вашем реестре в виде ключа metrics-registry :

Спасибо за прочтение!

  • 5 рекомендаций по оптимизации пул-реквестов
  • 10 полезных команд для командной строки и консоли
  • Установка и использование Snap-пакетов в Ubuntu 18.04

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *