Hardog's blog

trace forever

Group: 572218159
Email: 1273203953@qq.com
Location: hangzhou·zhejiang
GitHub: https://github.com/hardog

原文链接: 11 Simple npm Tricks

Using npm effectively can be difficult. There are a ton of features built-in, and it can be a daunting task to try to approach learning them.

高效率的使用npm是一项比较有挑战性的任务. 对于想尝试学习npm的人来说, npm内置的大量特性也会使人心生恐惧!

Personally, even learning and using just one of these tricks (npm prune, which is #4) saved me from getting rid of unused modules manually by deleting node_modules and re-installing everything with npm install. As you can probably imagine, that was insanely stressful.

于我个人而言, 仅仅学习和使用众多npm小技巧中的一个例如npm prune也能使我不用为重新安装模块和手动删除没有使用的模块而苦恼. 正如你可以想象的那样, 那真的能让人抓狂和倍感压力.

We’ve compiled this list of 11 simple-to-use npm tricks that will allow you to speed up development using npm, no matter what project you’re working on.

我们总结了11个npm的简单使用技巧, 无论你现在正在做着怎样的工作, 这些npm技巧的使用都将能够提高你的开发速度

1. Open a package’s homepage

打开npm包的首页

Run: npm home $package
执行命令: npm home 包名称

Running the home command will open the homepage of the package you’re running it against. Running against the lodash package will bring you to the Lodash website. This command can run without needing to have the package installed globally on your machine or within the current project.

运行npm home命令将会访问包所在的首页地址. 如果你运行npm home loadsh将会引导你访问到loadsh的首页地址. 运行该命令并不需要你在机器上全局安装模块, 也不需要当前所处的目录在你工程下面.

2. Open package’s GitHub repo

打开包的GitHub仓库地址

Run: npm repo $package
执行命令: npm repo 包名

Similar to home, the repo command will open the GitHub repository of the package you’re running it against. Running against the express package will bring you to the official Express repo. Also like home, you don’t need to have the package installed.

跟home命令一样, 执行repo命令将会打开该包所在的GitHub仓库地址. 例如如果你执行npm repo express将会引导你进入官方express仓库地址. 另外一点, 使用该命令同样也不需要你先安装包.

3. Check a package for outdated dependencies

检查过期的依赖包

Run: npm outdated
执行命令: npm outdated

You can run the outdated command within a project, and it will check the npm registry to see if any of your packages are outdated. It will print out a list in your command line of the current version, the wanted version, and the latest version.

你可以在一个项目中执行该命令, 然后该命令将会检查npm注册源与项目中的包进行比对从而判断出包是否过期. 最后将在命令行中打印出一个列表项该列表包含三个字段包的当前版本、期望的版本以及包的最新版本.

11_sample_npm_1

4. Check for packages not declared in package.json

检测出不在package.json中声明的包

Run: npm prune
执行命令: npm prune

When you run prune, the npm CLI will run through your package.json and compare it to your project’s /node_modules directory. It will print a list of modules that aren’t in your package.json.
当你运行该命令的时候, 该命令会比较工程目录下的node_modules模块与package.json声明的依赖. 最后会在命令行中打印出并未在package.json中声明的模块列表.

The npm prune command then strips out those packages, and removes any you haven’t manually added to package.json or that were npm installed without using the –save flag.
然后该命令会删除未添加到package.json文件者是安装包时没有带--save参数的包.

11_sample_npm_2

Update: Thanks to @EvanHahn for noticing a personal config setting that made npm prune provide a slightly different result than the default npm would provide!
更新: 感谢@EvanHahn带来的个人配置, 与npm默认行为相比使得该命令带来了不一样的展示结果

5. Lock down your dependencies versions

锁定依赖包版本

Run: npm shrinkwrap
执行命令: npm shrinkwrap

Using shrinkwrap in your project generates an npm-shrinkwrap.json file. This allows you to pin the dependencies of your project to the specific version you’re currently using within your node_modules directory. When you run npm install and there is a npm-shrinkwrap.json present, it will override the listed dependencies and any semver ranges in package.json.
在你的项目中使用shrinkwrap将会生成文件名为npm-shrinkwrap.json的文件. 该命令允许你固定你项目中正在使用包的具体版本. 运行该命令时将会生成npm-shrinkwrap.json文件, 当安装模块时如果目录下存在shrinkwrap文件, 将会优先使用该文件里面的包版本.

If you need verified consistency across package.json, npm-shrinkwrap.json and node_modules for your project, you should consider using npm-shrinkwrap.
如果你想验证package.json、npm-shrinkwrap.json和项目目录下的node_modules包的一致性, 你应该尝试使用npm-shrinkwrap包

11_sample_npm_3

6. Use npm v3 with Node.js v4 LTS

在Nodejs v4 LTS版本中使用第三版的npm

Run: npm install -g npm@3

Installing npm@3 globally with npm will update your npm v2 to npm v3, including on the Node.js v4 LTS release (“Argon”) ships with the npm v2 LTS release. This will install the latest stable release of npm v3 within your v4 LTS runtime.
全局安装npm3会将你本地的npm2升级到npm3版本, 包括Nodejs4 LTS附带的npm2 LTS. 该命令将在Nodejs v4 LTS版本中安装最新的npm v3稳定版本.

7. Allow npm install -g without needing sudo

免sudo全局安装模块

Run: npm config set prefix $dir
执行命令: npm config set prefix 目录

After running the command, where $dir is the directory you want npm to install your global modules to, you won’t need to use sudo to install modules globally anymore. The directory you use in the command becomes your global bin directory. The only caveat: you will need to make sure you adjust your user permissions for that directory with chown -R $USER $dir.
执行该命令后, $dir目录将成为npm安装全局模块的默认路径, 再也不需要使用sudo来安装全局模块了. 你在命令行设置的路径将成为全局bin目录. 你唯一需要注意的是: 你需要使用命令chown -R $USER $dir命令来改变目录的用户权限.

8. Change the default save prefix for all your projects

改变包安装时保存到package.json模块的版本前缀

Run: npm config set save-prefix ~

The tilde (~) is more conservative than what npm defaults to, the caret (^), when installing a new package with the –save or –save-dev flags. The tilde pins the dependency to the minor version, allowing patch releases to be installed with npm update. The caret pins the dependency to the major version, allowing minor releases to be installed with npm update.
波浪符号相比npm默认的保存包安装前缀插入符号更保守. 波浪符号会固定住次版本号, 当执行npm update命令时允许升级patch版本, 而插入符号固定的是主版本号, 当执行npm update命令时允许更新次版本号.

9. Strip your project’s devDependencies for a production environment

生产环境中跳过开发依赖包

When your project is ready for production, make sure you install your packages with the added –production flag. The –production flag installs your dependencies, ignoring your devDependencies. This ensures that your development tooling and packages won’t go into the production environment.
当你的项目准备上线, 在安装依赖包的时候带上--production参数. 该参数会忽略开发依赖包, 这个功能能够确保在你开发环境中的一些开发工具以及开发时依赖的包不会被安装到线上环境.

Additionally, you can set your NODE_ENV environment variable to production to ensure that your project’s devDependencies are never installed.
另外, 你也可以通过在生产环境中设置NODE_ENV环境变量来确保每次安装依赖包的时候都不会安装只有开发环境才依赖的包.

10. Be careful when using .npmignore

小心的使用.npmignore

If you haven’t been using .npmignore, it defaults to .gitignore with a few additional sane defaults.
如果你还没有使用.npmignore文件, 默认.gitignore文件会提供一些额外的功能

What many don’t realize that once you add a .npmignore file to your project the .gitignore rules are (ironically) ignored. The result is you will need to audit the two ignore files in sync to prevent sensitive leaks when publishing.
许多人可能没有意识到, 一旦你在项目中添加.npmignore文件, .gitignore规则就会被忽略, 这很讽刺. 结果是你需要同步的审计ignore文件以防止在发布时泄漏敏感信息.

11. Automate npm init with defaults

使得npm init默认自动初始化

When you run npm init in a new project, you’re able to go through and set up your package.json’s details. If you want to set defaults that npm init will always use, you can use the config set command, with some extra arguments:
当你使用npm init来开始一个新项目时, 你可以通过该初始化命令来设置package.json文件. 如果你每次在npm init时都有一些默认参数需要设置, 你可以使用以下附带参数的配置命令:

1
npm config set init.author.name $name  
npm config set init.author.email $email

If, instead, you want to completely customize your init script, you can point to a self-made default init script by running
然后, 如果你想完全的自定义你的init脚本, 你可以使用如下命令指向你的自定义脚本

1
npm config set init-module ~/.npm-init.js`

Here’s a sample script that prompts for private settings and creates a GitHub repo if you want. Make sure you change the default GitHub username (YOUR_GITHUB_USERNAME) as the fallback for the GitHub username environment variable.
以下是一个简单的样例脚本来创建GitHub仓库, 以及如果有需要会有提示让你输入一些私人的设置. 使用之前请确保你修改了GitHub的用户名

1
var cp = require('child_process');  
var priv;

var USER = process.env.GITHUB_USERNAME || 'YOUR_GITHUB_USERNAME';

module.exports = {

  name: prompt('name', basename || package.name),

  version: '0.0.1',

  private: prompt('private', 'true', function(val){
    return priv = (typeof val === 'boolean') ? val : !!val.match('true')
  }),

  create: prompt('create github repo', 'yes', function(val){
    val = val.indexOf('y') !== -1 ? true : false;

    if(val){
      console.log('enter github password:');
      cp.execSync("curl -u '"+USER+"' https://api.github.com/user/repos -d " +
        "'{\"name\": \""+basename+"\", \"private\": "+ ((priv) ? 'true' : 'false')  +"}' ");
      cp.execSync('git remote add origin '+ 'https://github.com/'+USER+'/' + basename + '.git');
    }

    return undefined;
  }),

  main: prompt('entry point', 'index.js'),

  repository: {
    type: 'git',
    url: 'git://github.com/'+USER+'/' + basename + '.git' },

  bugs: { url: 'https://github.com/'+USER+'/' + basename + '/issues' },

  homepage: "https://github.com/"+USER+"/" + basename,

  keywords: prompt(function (s) { return s.split(/\s+/) }),

  license: 'MIT',

  cleanup: function(cb){

    cb(null, undefined)
  }

}

One last thing…

If you want to learn more about npm, Node.js, JavaScript, Docker, Kubernetes, Electron, and tons more, you should follow @NodeSource on Twitter. We’re always around and would love to hear from you!