乐闻世界logo
搜索文章和话题

How to create tgz file with version using npm pack?

1个答案

1

In software development, creating a .tgz file using npm (Node Package Manager) is a common requirement to distribute or deploy a codebase as a package. Below are the specific steps and examples:

Step 1: Prepare the package.json file

Ensure your project has a valid package.json file. This file describes the project's dependencies, scripts, version information, and other metadata. If your project lacks this file, create it by running the npm init command and following the prompts to fill in project details.

Step 2: Write your code

Develop the project's functionality and save the code in the project folder. Ensure the code is clear, efficient, and thoroughly tested.

Step 3: Use the npm pack command to package

In your project's root directory, open a command-line tool (such as cmd or Terminal) and execute the following command:

bash
npm pack

This command packages your project into a .tgz file. It includes all files specified in the files array of the package.json file. If no files array is defined, it defaults to including all files except those listed in .gitignore.

Example

Assume you have a project with the following structure:

shell
/my-npm-project/ |-- src/ | |-- index.js | |-- helper.js |-- test/ | |-- test.js |-- package.json |-- .npmignore

The package.json might look like this:

json
{ "name": "my-npm-project", "version": "1.0.0", "description": "A sample npm package", "main": "src/index.js", "scripts": { "test": "node test/test.js" }, "author": "Your Name", "license": "ISC" }

If the .npmignore file includes test/, this directory will be excluded from the .tgz file.

After running npm pack, you will find a file named my-npm-project-1.0.0.tgz in the project root directory.

Step 4: Verify the package contents

To inspect the contents of the .tgz file, use the tar command:

bash
tar -tvf my-npm-project-1.0.0.tgz

This will list all files and directories within the packaged archive, allowing you to confirm that all necessary files are included.

By following these steps, you can successfully create a .tgz file using npm, suitable for distributing or version controlling npm packages.

2024年6月29日 12:07 回复

你的答案