Component encapsulation: TS + Vue: Encapsulates publishable components

Writing a declaration file, Scopes packages, and publishing them to NPM.

Declaration file

Since the built file is a JS file, a declaration file is required to reference it in the TS project.

package.json

When adding a declaration file to a library, there is a field called types in package.json that specifies the entry path to the declaration file:

// package.json

{
  // ...
  "types": "./types/employee-query.d.ts"
}
Copy the code

employee-query.d.ts

Write a declaration file for the UMD class library. See how to import external class libraries in TypeScript. How to write declaration file? / declaration file/UMD class library

import Vue from "vue";

declare class EmployeeQuery extends Vue {
  // Add a member
  name: string;
  selected: number;
  department: { department: string; departmentId: number} []; query():void;
}

export as namespaceEmployeeQuery; // The umD library declares that this statement is necessary. export = EmployeeQuery;Copy the code

Published to the NPM

Log in to the NPM

$ npm login
Copy the code

Enter the account password email address step by step

npm notice Log in on https://registry.npmjs.org/
Username:
Password:
Email: (this IS public)
Logged in as XXXX on https://registry.npmjs.org/.
Copy the code

Publish using scope packs (Scopes)

The NPM version is greater than 2.7.0

To solve the problem of “I can’t figure out the package name because the package name is already in use”, I decided to use the scope package.

A scope package is a namespace, and if the package name starts with @, it’s a scope package, for example

@scope/project-name
Copy the code

Each NPM user has its own scope, and the scope name is the user name.

@username/project-name
Copy the code

Transform the package name

// package.json
{
  "name": "@username/project-name"
}
Copy the code

Or in NPM init, add

$ npm init --scope=username
Copy the code

release

By default, the scope package is private. To publish a private module, you need to pay. But the common module is free 😊

npm publish --access=public
Copy the code

After successful publishing, you can manage your own packages at www.npmjs.com/.