The Ins and Outs of preinstall
约 2 分钟阅读
1. Overview
preinstall is a hook in npm scripts. There's also postinstall. Their execution order is as follows — easier to compare side by side:
- preinstall
- install
- postinstall
2. preinstall vs postinstall
Differences and what each is for
- The names are self-explanatory:
postruns afternpm install,preruns beforenpm install. preinstallonly runs onnpm install, not on other npm commands.postinstallruns not only onnpm installbut also onnpm install xxxandnpm update.preinstallis good for setup work — checking the Node and npm environment, installing related dependencies, and so on.postinstallis good for compilation and initialization scripts.
3. Some Optimizations
Adding a Shebang (Hashbang)
- In computing, a Shebang (also known as a Hashbang) is the character sequence consisting of a number sign and an exclamation mark —
#!— that appears as the first two characters on the first line of a text file. When a Shebang is present, the program loader on a Unix-like operating system parses what comes after the Shebang as an interpreter directive, invokes that interpreter, and passes the path of the file containing the Shebang as an argument to the interpreter. For example, a file starting with#!/bin/shwill, when executed, actually invoke the /bin/sh program (typically the Bourne shell or a compatible shell such as bash, dash, and so on) to execute it. This line is also the standard first line of a shell script. Since#is a comment marker in many scripting languages, the Shebang content is automatically ignored by their interpreters. In languages where#isn't a comment marker — like Scheme — interpreters may still ignore a leading#!line for compatibility with Shebangs. The name "Shebang" or "Hashbang" is sometimes also used for fragment identifiers in Ajax applications, used by browsers for state preservation; Google Webmaster Central noted that fragment identifiers starting with an exclamation mark (i.e.,...url#!state...) would be indexed by Google's crawler.
Add #!/usr/bin/env node to the front of the script.
Adding #!/usr/bin/env node as the first line of a script tells the operating system to use the Node.js interpreter to execute it. The benefit is that you can run the script directly without explicitly specifying the interpreter on the command line — making the script more convenient and self-executable.
For example, with #!/usr/bin/env node, you can run ./script.js directly instead of node script.js.
mainonly runs when the script is executed, not when it's imported viarequire
if (require.main === module) {
main()
}
// main 中执行你需要执行的相关逻辑