当前位置: 首页 > 工具软件 > local-npm > 使用案例 >

学习笔记 - npm依赖管理 npm dependency

吴经略
2023-12-01

ref: https://nodejs.dev/an-introduction-to-the-npm-package-manager
基本来自官网,链接如上。为了加深理解和印象稍作整理如下:

1. Node.js

1.1 Difference between Node.js and Browser

  1. Can use JS to write backend…
  1. In the browser, most of the time what you are doing is interacting with the DOM, or other Web Platform APIs like Cookies. Those do not exist in Node.js, of course. You don’t have the document, window and all the other objects that are provided by the browser.
    And in the browser, we don’t have all the nice APIs that Node.js provides through its modules, like the filesystem access functionality.
  1. Another big difference is that in Node.js you control the environment, you know which version of Node.js you will run the application on.
    Compared to the browser environment, where you don’t get the luxury to choose what browser your visitors will use
  1. Since JavaScript moves so fast, but browsers can be a bit slow and users a bit slow to upgrade, You can use Babel to transform your code to be ES5-compatible before shipping it to the browser, but in Node.js, you won’t need that.
  1. Another difference is that Node.js uses the CommonJS module system, while in the browser we are starting to see the ES Modules standard being implemented.

2. V8 Javascript Engine

2.1 V8 Intro

  1. V8 is the name of the JavaScript engine that powers Google Chrome. It’s the thing that takes our JavaScript and executes it while browsing with Chrome.
  2. V8 provides the runtime environment in which JavaScript executes. The DOM, and the other Web Platform APIs are provided by the browser.
    The cool thing is that the JavaScript engine is independent of the browser in which it’s hosted.

2.2 Other JS Engines

Other browsers have their own JavaScript engine:

Firefox has SpiderMonkey
Safari has JavaScriptCore (also called Nitro)
Edge has Chakra

3. Node.js Program

node app.js  // run

process.exit(1)  // or:
process.exitCode = 1

// sometimes need:
process.on('SIGTERM', () => {  // SIGTERM is the signal that tells a process to gracefully terminate
  server.close(() => {
    console.log('Process terminated')
  })
})
// or
process.kill(process.pid, 'SIGTERM')

4. Read environment variables from Node.js

process.env.NODE_ENV // "development" // is set to development by default.
// Setting it to "production" before the script runs will tell Node.js that this is a production environment.
// also can access customer env in the same way

5. Where to host a Node.js app

6. How to use the Node.js REPL

7. Node.js, accept arguments from the command line

8. Output to the command line using Node.js

9. Accept input from the command line in Node.js

10. Expose functionality from a Node.js file using exports

  • module.exports
    The first is to assign an object to module.exports, which is an object provided out of the box by the module system, and this will make your file export just that object:
const car = {
  brand: 'Ford',
  model: 'Fiesta'
}
module.exports = car

//..in the other file
const car = require('./car')
  • exports
    The second way is to add the exported object as a property of exports. This way allows you to export multiple objects, functions or data:
const car = {
  brand: 'Ford',
  model: 'Fiesta'
}
exports.car = car
// or:
exports.car = {
  brand: 'Ford',
  model: 'Fiesta'
}
//..in the other file
const car = require('./items').car
  • Difference between these two:
    The first exposes the object it points to. The latter exposes the properties of the object it points to.

11. Introduction to npm

11.1 Introduction

npm is the standard package manager for Node.js.
Yarn is an alternative to npm.

11.2 Downloads

// if package.json exists
npm install  // install everything the project needs, in the node_modules folder
npm install <package-name>
npm install <package-name> --save // installs and adds the entry to the package.json file dependencies
npm install <package-name> --save-dev // installs and adds the entry to the package.json file devDependencies
npm update // npm will check all packages for a newer version that satisfies your versioning constraints.
npm update <package-name> 

11.3 Versioning

the whole team runs the same version until the package.json file is updated.

11.4 Running Tasks

package.json file supports a format for specifying command line tasks that can be run by using npm run <task-name>

{
  "scripts": {
    "watch": "webpack --watch --progress --colors --config webpack.conf.js",
    "dev": "webpack --progress --colors --config webpack.conf.js",
    "prod": "NODE_ENV=production webpack -p --config webpack.conf.js",
  },
}
// instead of typing those long commands, can do:
$ npm run watch
$ npm run dev
$ npm run prod

12. local and global install

local: the package is installed in the current file tree, under the node_modules subfolder.
global: The npm root -gcommand will tell you where that exact location is on your machine.

13. How to use or execute a package installed using npm

const _ = require('lodash')

Above is used in Node.js, in browser, use import:

import {useDispatch} from "react-redux"

14. The package.json guide

14.1 File Structure

{
  "name": "test-project",  // sets the application/package name
  // tells the name of the app, or package, that's contained in the same folder where this file lives.
  // 大概就是和package.json文件在同一目录下的app name?
  "version": "1.0.0",  // indicates the current version
  "description": "A Vue.js project", // is a brief description of the app/package
  "main": "src/main.js", // set the entry point for the application
  "private": true, // if set to true prevents the app/package to be accidentally published on npm
  "scripts": { // defines a set of node scripts you can run
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "unit": "jest --config test/unit/jest.conf.js --coverage",
    "test": "npm run unit",
    "lint": "eslint --ext .js,.vue src test/unit",
    "build": "node build/build.js"
  }, 
  "dependencies": { // sets a list of npm packages installed as dependencies
    "vue": "^2.5.2"
  },
  "devDependencies": { // sets a list of npm packages installed as development dependencies
    "autoprefixer": "^7.1.2",
    "babel-core": "^6.22.1",
    "babel-eslint": "^8.2.1",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    ...
  },
  "engines": { // sets which versions of Node.js this package/app works on
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": ["> 1%", "last 2 versions", "not ie <= 8"] // tell which browsers (and their versions) you want to support
}

14.2 Properties breakdown

Omit: Describe in detail how to write a package.json file
BTW, The package.json file can also host command-specific configuration, for example for Babel, ESLint, and more.

14.3 Package versions

  • ~: if you write ~0.13.0, you want to only update patch releases: 0.13.1 is ok, but 0.14.0 is not.
  • ^: if you write ^0.13.0, you want to update patch and minor releases: 0.13.1, 0.14.0 and so on.
  • *: if you write *, that means you accept all updates, including major version upgrades.
  • no symbol: you accept only that specific version you specify
  • latest: you want to use the latest version available
    1.0.0 || >=1.1.0 <1.2.0, to either use 1.0.0 or one release from 1.1.0 up, but lower than 1.2.0.

15. The package-lock.json file

https://nodejs.dev/the-package-lock-json-file

  • You don’t commit to Git your node_modules folder, which is generally huge, when replicate the project, for example:
    if you specified the ~ syntax in package.json, and a patch release of a package has been released, which means 0.13.0 can be 0.13.1 now, that new one is going to be installed.

  • The package-lock.json sets your currently installed version of each package in stone, and npm will use those exact versions when running npm install

  • The package-lock.json file needs to be committed to your Git repository, so it can be fetched by other people

  • The dependencies versions will be updated in the package-lock.json file when you run npm update.

ISSUE: 当我们npm install时,用的是package.json还是package-lock.json呢???
Some says when run npm install, package.json overrides package-lock,jsonfor newer version automatically. Then someone says upon new version npm 5.1.0, the behavior of package-lock.json changed, then someone provides: upon version 5.7.1, there is a new command npm ciwhich will install from package-lock.json.

16. Find the installed version of an npm package

To see the latest version of all the npm package installed, including their dependencies:

❯ npm list
/Users/joe/dev/node/cowsay
└─┬ cowsay@1.3.1
  ├── get-stdin@5.0.1
  ├─┬ optimist@0.6.1
  │ ├── minimist@0.0.10
  │ └── wordwrap@0.0.3
  ├─┬ string-width@2.1.1
  │ ├── is-fullwidth-code-point@2.0.0
  │ └─┬ strip-ansi@4.0.0
  │   └── ansi-regex@3.0.0
  └── strip-eof@1.0.0

And more…

17. Install an older version of an npm package

npm install <package>@<version>
npm install cowsay
npm install cowsay@1.2.0
npm view cowsay versions

18. Update all the Node.js dependencies to their latest version

npm update

for example, we have ^1.3.1 in package.json, after npm update, package.json stays the same, package-lock.json may change.

npm outdated // To discover new releases of the packages

Some of those updates are major releases. Running npm update won’t update the version of those.

我的理解是:像补丁类的,13.0.0到13.0.1,可以通过npm update,像主要的版本发布,比如13.0.0到14.0.0,就要用下面这种方法了:

To update to a new major version all the packages, install the npm-check-updates package globally:

// 如果你实在想要新版本,而不用发布的主要版本:
npm install -g npm-check-updates
ncu -u
npm update // if don't have node_modules, instead, can run: 
(npm install)

19. Semantic Versioning using npm

20. Uninstalling npm packages

21. npm global or local packages

22. npm dependencies and devDependencies

The package is automatically listed in the package.json file, under the dependencieslist (as of npm 5: before you had to manually specify --save).

When you add the -D flag, or --save-dev, you are installing it as a development dependency, which adds it to the devDependencieslist.

"dependencies": {
	"jquery": "3.1.0",
	...
},
"devDependencies": {
	...
}

Development dependenciesare intended as development-only packages, that are unneeded in production. For example testing packages, webpack or Babel.

  • When you go in production, if you type npm install and the folder contains a package.json file, they are installed, as npm assumes this is a development deploy.
  • You need to set the --productionflag (npm install --production) to avoidinstalling those development dependencies.
  • My understanding here is, it will install devDependencies in production, if you directly use npm install without --production argument.
  • As a reminder, if there are package.json in the folder, then npm install will know these files and read it, then to download the dependencies defined in a package.json file and generates a node_modules folder with the installed modules.

… Too much things, I just stop here

 类似资料: