Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
scripts.md367 linesDownload Raw Back to using-npm
1---
2title: Scripts
3section: 7
4description: How npm handles the "scripts" field
5---
6
7### Description
8
9The `"scripts"` property of your `package.json` file supports a number of built-in scripts and their preset life cycle events as well as arbitrary scripts.
10These all can be executed by running `npm run <stage>`.
11*Pre* and *post* commands with matching names will be run for those as well (e.g.
12`premyscript`,
13`myscript`, `postmyscript`).
14Scripts from dependencies can be run with `npm explore <pkg> -- npm run <stage>`.
15
16### Pre & Post Scripts
17
18To create "pre" or "post" scripts for any scripts defined in the
19`"scripts"` section of the `package.json`, simply create another script
20*with a matching name* and add "pre" or "post" to the beginning of them.
21
22```json
23{
24  "scripts": {
25    "precompress": "{{ executes BEFORE the `compress` script }}",
26    "compress": "{{ run command to compress files }}",
27    "postcompress": "{{ executes AFTER `compress` script }}"
28  }
29}
30```
31
32In this example `npm run compress` would execute these scripts as described.
33
34### Life Cycle Scripts
35
36There are some special life cycle scripts that happen only in certain situations.
37These scripts happen in addition to the `pre<event>`, `post<event>`, and
38`<event>` scripts.
39
40* `prepare`, `prepublish`, `prepublishOnly`, `prepack`, `postpack`, `dependencies`
41
42**prepare** (since `npm@4.0.0`)
43* Runs BEFORE the package is packed, i.e.
44during `npm publish` and `npm pack`
45* Runs on local `npm install` without package arguments (runs with flags like `--production` or `--omit=dev`, but does not run when installing specific packages like `npm install express`)
46* Runs AFTER `prepublishOnly` and `prepack`, but BEFORE `postpack`
47* Runs for a package if it's being installed as a link through `npm install <folder>`
48
49* NOTE: If a package being installed through git contains a `prepare` script, its `dependencies` and `devDependencies` will be installed, and the prepare script will be run, before the package is packaged and installed.
50
51* As of `npm@7` these scripts run in the background.
52  To see the output, run with: `--foreground-scripts`.
53
54* **In workspaces, prepare scripts run concurrently** across all packages. If you have interdependent packages where one must build before another, consider using `--foreground-scripts` (which can be set in `.npmrc` with `foreground-scripts=true`) to run scripts sequentially, or structure your build differently.
55
56**prepublish** (DEPRECATED)
57* Does not run during `npm publish`, but does run during `npm ci` and `npm install`.
58See below for more info.
59
60**prepublishOnly**
61* Runs BEFORE the package is prepared and packed, ONLY on `npm publish`.
62
63**prepack**
64* Runs BEFORE a tarball is packed (on "`npm pack`", "`npm publish`", and when installing a git dependency).
65* NOTE: "`npm run pack`" is NOT the same as "`npm pack`". "`npm run pack`" is an arbitrary user defined script name, whereas, "`npm pack`" is a CLI defined command.
66
67**postpack**
68* Runs AFTER the tarball has been generated but before it is moved to its final destination (if at all, publish does not save the tarball locally)
69
70**dependencies**
71* Runs AFTER any operations that modify the `node_modules` directory IF changes occurred.
72* Does NOT run in global mode
73
74#### Prepare and Prepublish
75
76**Deprecation Note: prepublish**
77
78Since `npm@1.1.71`, the npm CLI has run the `prepublish` script for both `npm publish` and `npm install`, because it's a convenient way to prepare a package for use (some common use cases are described in the section below).
79It has also turned out to be, in practice, [very confusing](https://github.com/npm/npm/issues/10074).
80As of `npm@4.0.0`, a new event has been introduced, `prepare`, that preserves this existing behavior.
81A _new_ event, `prepublishOnly` has been added as a transitional strategy to allow users to avoid the confusing behavior of existing npm versions and only run on `npm publish` (for instance, running the tests one last time to ensure they're in good shape).
82
83See <https://github.com/npm/npm/issues/10074> for a much lengthier justification, with further reading, for this change.
84
85**Use Cases**
86
87Use a `prepare` script to perform build tasks that are platform-independent and need to run before your package is used.
88This includes tasks such as:
89
90* Compiling TypeScript or other source code into JavaScript.
91* Creating minified versions of JavaScript source code.
92* Fetching remote resources that your package will use.
93
94Running these build tasks in the `prepare` script ensures they happen once, in a single place, reducing complexity and variability.
95Additionally, this means that:
96
97* You can depend on build tools as `devDependencies`, and thus your users don't need to have them installed.
98* You don't need to include minifiers in your package, reducing the size for your users.
99* You don't need to rely on your users having `curl` or `wget` or other system tools on the target machines.
100
101#### Dependencies
102
103The `dependencies` script is run any time an `npm` command causes changes to the `node_modules` directory.
104It is run AFTER the changes have been applied and the `package.json` and `package-lock.json` files have been updated.
105
106### Life Cycle Operation Order
107
108#### [`npm cache add`](/commands/npm-cache)
109
110* `prepare`
111
112#### [`npm ci`](/commands/npm-ci)
113
114* `preinstall`
115* `install`
116* `postinstall`
117* `prepublish`
118* `preprepare`
119* `prepare`
120* `postprepare`
121
122These all run after the actual installation of modules into
123 `node_modules`, in order, with no internal actions happening in between
124
125#### [`npm diff`](/commands/npm-diff)
126
127* `prepare`
128
129#### [`npm install`](/commands/npm-install)
130
131These also run when you run `npm install -g <pkg-name>`
132
133* `preinstall`
134* `install`
135* `postinstall`
136* `prepublish`
137* `preprepare`
138* `prepare`
139* `postprepare`
140
141If there is a `binding.gyp` file in the root of your package and you haven't defined your own `install` or `preinstall` scripts, npm will default the `install` command to compile using node-gyp via `node-gyp rebuild`
142
143These are run from the scripts of `<pkg-name>`
144
145#### [`npm pack`](/commands/npm-pack)
146
147* `prepack`
148* `prepare`
149* `postpack`
150
151#### [`npm publish`](/commands/npm-publish)
152
153* `prepublishOnly`
154* `prepack`
155* `prepare`
156* `postpack`
157* `publish`
158* `postpublish`
159
160#### [`npm rebuild`](/commands/npm-rebuild)
161
162* `preinstall`
163* `install`
164* `postinstall`
165* `prepare`
166
167`prepare` is only run if the current directory is a symlink (e.g.
168with linked packages)
169
170#### [`npm restart`](/commands/npm-restart)
171
172If there is a `restart` script defined, these events are run; otherwise,
173`stop` and `start` are both run if present, including their `pre` and `post` iterations)
174
175* `prerestart`
176* `restart`
177* `postrestart`
178
179#### [`npm run <user defined>`](/commands/npm-run)
180
181* `pre<user-defined>`
182* `<user-defined>`
183* `post<user-defined>`
184
185#### [`npm start`](/commands/npm-start)
186
187* `prestart`
188* `start`
189* `poststart`
190
191If there is a `server.js` file in the root of your package, then npm will default the `start` command to `node server.js`.
192`prestart` and `poststart` will still run in this case.
193
194#### [`npm stop`](/commands/npm-stop)
195
196* `prestop`
197* `stop`
198* `poststop`
199
200#### [`npm test`](/commands/npm-test)
201
202* `pretest`
203* `test`
204* `posttest`
205
206#### [`npm version`](/commands/npm-version)
207
208* `preversion`
209* `version`
210* `postversion`
211
212#### A Note on a lack of [`npm uninstall`](/commands/npm-uninstall) scripts
213
214While npm v6 had `uninstall` lifecycle scripts, npm v7 does not.
215Removal of a package can happen for a wide variety of reasons, and there's no clear way to currently give the script enough context to be useful.
216
217
218Reasons for a package removal include:
219
220* a user directly uninstalled this package
221* a user uninstalled a dependent package and so this dependency is being uninstalled
222* a user uninstalled a dependent package but another package also depends on this version
223* this version has been merged as a duplicate with another version
224* etc.
225
226Due to the lack of necessary context, `uninstall` lifecycle scripts are not implemented and will not function.
227
228### Working Directory for Scripts
229
230Scripts are always run from the root of the package folder, regardless of what the current working directory is when `npm` is invoked.
231This means your scripts can reliably assume they are running in the package root.
232
233If you want your script to behave differently based on the directory you were in when you ran `npm`, you can use the `INIT_CWD` environment variable, which holds the full path you were in when you ran `npm run`.
234
235#### Historical Behavior in Older npm Versions
236
237For npm v6 and earlier, scripts were generally run from the root of the package, but there were rare cases and bugs in older versions where this was not guaranteed.
238If your package must support very old npm versions, you may wish to add a safeguard in your scripts (for example, by checking process.cwd()).
239
240For more details, see:
241- [npm v7 release notes](https://github.com/npm/cli/releases/tag/v7.0.0)
242- [Discussion about script working directory reliability in npm v6 and earlier](https://github.com/npm/npm/issues/12356)
243
244### Environment
245
246Package scripts run in an environment where many pieces of information are made available regarding the setup of npm and the current state of the process.
247
248#### path
249
250If you depend on modules that define executable scripts, like test suites, then those executables will be added to the `PATH` for executing the scripts.
251So, if your package.json has this:
252
253```json
254{
255  "name" : "foo",
256  "dependencies" : {
257    "bar" : "0.1.x"
258  },
259  "scripts": {
260    "start" : "bar ./test"
261  }
262}
263```
264
265then you could run `npm start` to execute the `bar` script, which is exported into the `node_modules/.bin` directory on `npm install`.
266
267#### package.json vars
268
269npm sets the following environment variables from the package.json:
270
271* `npm_package_name` - The package name
272* `npm_package_version` - The package version
273* `npm_package_bin_*` - Each executable defined in the bin field
274* `npm_package_engines_*` - Each engine defined in the engines field
275* `npm_package_config_*` - Each config value defined in the config field
276* `npm_package_json` - The full path to the package.json file
277
278Additionally, for install scripts (`preinstall`, `install`, `postinstall`), npm sets these environment variables:
279
280* `npm_package_resolved` - The resolved URL for the package
281* `npm_package_integrity` - The integrity hash for the package
282* `npm_package_optional` - Set to `"true"` if the package is optional
283* `npm_package_dev` - Set to `"true"` if the package is a dev dependency
284* `npm_package_peer` - Set to `"true"` if the package is a peer dependency
285* `npm_package_dev_optional` - Set to `"true"` if the package is both dev and optional
286
287For example, if you had `{"name":"foo", "version":"1.2.5"}` in your package.json file, then your package scripts would have the `npm_package_name` environment variable set to "foo", and the `npm_package_version` set to "1.2.5". You can access these variables in your code with `process.env.npm_package_name` and `process.env.npm_package_version`.
288
289**Note:** In npm 7 and later, most package.json fields are no longer provided as environment variables. Scripts that need access to other package.json fields should read the package.json file directly. The `npm_package_json` environment variable provides the path to the file for this purpose.
290
291See [`package.json`](/configuring-npm/package-json) for more on package configs.
292
293#### current lifecycle event
294
295Lastly, the `npm_lifecycle_event` environment variable is set to whichever stage of the cycle is being executed.
296So, you could have a single script used for different parts of the process which switches based on what's currently happening.
297
298Objects are flattened following this format, so if you had
299`{"scripts":{"install":"foo.js"}}` in your package.json, then you'd see this in the script:
300
301```bash
302process.env.npm_package_scripts_install === "foo.js"
303```
304
305### Examples
306
307For example, if your package.json contains this:
308
309```json
310{
311  "scripts" : {
312    "prepare" : "scripts/build.js",
313    "test" : "scripts/test.js"
314  }
315}
316```
317
318then `scripts/build.js` will be called for the prepare stage of the lifecycle, and you can check the
319`npm_lifecycle_event` environment variable if your script needs to behave differently in different contexts.
320
321If you want to run build commands, you can do so.
322This works just fine:
323
324```json
325{
326  "scripts" : {
327    "prepare" : "npm run build",
328    "build" : "tsc",
329    "test" : "jest"
330  }
331}
332```
333
334### Exiting
335
336Scripts are run by passing the line as a script argument to `/bin/sh` on POSIX systems or `cmd.exe` on Windows.
337You can control which shell is used by setting the [`script-shell`](/using-npm/config#script-shell) configuration option.
338
339If the script exits with a code other than 0, then this will abort the process.
340
341Note that these script files don't have to be Node.js or even JavaScript programs.
342They just have to be some kind of executable file.
343
344### Best Practices
345
346* Don't exit with a non-zero error code unless you *really* mean it.
347  If the failure is minor or only will prevent some optional features, then it's better to just print a warning and exit successfully.
348* Try not to use scripts to do what npm can do for you.
349Read through [`package.json`](/configuring-npm/package-json) to see all the things that you can specify and enable by simply describing your package appropriately.
350In general, this will lead to a more robust and consistent state.
351* Inspect the env to determine where to put things.
352For instance, if the `NPM_CONFIG_BINROOT` environment variable is set to `/home/user/bin`, then don't try to install executables into `/usr/local/bin`.
353The user probably set it up that way for a reason.
354* Don't prefix your script commands with "sudo".  If root permissions are required for some reason, then it'll fail with that error, and the user will sudo the npm command in question.
355* Don't use `install`.
356Use a `.gyp` file for compilation, and `prepare` for anything else.
357You should almost never have to explicitly set a preinstall or install script.
358If you are doing this, please consider if there is another option.
359The only valid use of `install` or `preinstall` scripts is for compilation which must be done on the target architecture.
360
361### See Also
362
363* [npm run](/commands/npm-run)
364* [package.json](/configuring-npm/package-json)
365* [npm developers](/using-npm/developers)
366* [npm install](/commands/npm-install)
367 
codekingpro/portable-devtools · Team Ai