This is the 24th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

background

Learning the front end of three months, ready to brush interview questions, summary summary, a few interview questions a day, to the big factory.

One day, a classmate asked me, I want to write a toolkit, release to THE NPM, and then directly NPM installation package, direct command, you can trigger the function of the package.

How do you write this? It’s an NPM kit!

“Don’t panic, I’ll teach you,” I said

Read all picture addresses in Lottie. Json animation

  1. First we should understand the necessary files for a simple NPM package.
  2. Commands for configuring the tool package
  3. Code reads user interaction command input
  4. Implement tool package functions based on user input.

NPM toolkit required files

  1. package.json
  2. README.md
  3. index.js

Simple, in fact, three files can make an NPM package.

Package. json is mainly used to configure your toolkit name, version, to your commands, toolkit dependencies, etc. We just do NPM init. The package.json file is automatically generated when you fill in the file as prompted.

Readme.md why do you need this file? In fact, this file is not necessary, but we as a toolkit, is to provide others to use, this is equivalent to the manual, otherwise your toolkit no matter how great, others will not use, can only be frozen.

Index. js is our code file. We are writing code to run in the Node environment, so we need to add:

#! /usr/bin/env node

Open to

  1. We generated the package.json file using NPM init
    {
        "name": "lottie-extract-assets"."version": "1.0.3"."description": "According to Lottie configuration file, extract Lottie JSON file image, output configuration"."main": "index.js"."scripts": {
            "lottieExtract": "node ./index.js"
        },
        "bin": {
            "lottieExtract": "./index.js"
        },
        "repository": {
            "type": "git"."url": "https://github.com.cnpmjs.org/qyjandroid/lottie-extract-assets.git"
        },
        "keywords": [
            "lottie"."Resource extraction"."Image extraction"]."author": "quanyj"."license": "ISC"."dependencies": {
            "commander": "^ 7.2.0"."inquirer": "^ 8.0.0." "."request": "^ 2.88.2"}}Copy the code

Note one configuration: the bin field

The bin field is used to configure what commands someone else executes to trigger our script.

For example, here I configure:

    "bin": {
            "lottieExtract": "./index.js"
        },
Copy the code

At this point, when someone uses my toolkit, simply type lottieExtract on the command line to execute my toolkit script.

  1. Write the function index.js

Since we need to extract Lottie. Json file, we need to interact with the user about which JSON file to extract, which file name to output or which directory to save to, so we need to use two libraries here:

  • Commander.js The complete Node.js command line solution
  • Inquirer. Js a set of generic interactive command-line user interfaces.

First we install the two toolkits:

    cnpm install commander inquirer -D
Copy the code

Our code to achieve functional steps:

  1. We first look for the default in the context of the current installation packagelottie-extract-assets.jsonFile.
  2. If not, we will prompt the user to enter interactive command, according to the user input configuration to implement the function.
  3. If we find it,lottie-extract-assets.jsonGenerate the default configuration, according to the configuration to achieve the function.

Code implementation:

    #!/usr/bin/env node
    // Use fs for file operations
    const fs = require('fs');
    const request = require('request');
    const path = require('path');
    const program = require('commander');
    const inquirer = require('inquirer');
    const cwd = process.cwd();

    // The configuration file read by default
    const defaultConfigJsonName="lottie-extract-assets.json";
    const defaultConfigJson =path.join(cwd,defaultConfigJsonName);
    console.log("Read configuration file:",defaultConfigJson);
    // Read the default configuration file
    readJsonFile(defaultConfigJson).then((result) = >{
        // If the configuration file exists, extract it
        if(result){
            startAssetsExtract(result);
        }else{
            // The default configuration file does not exist. The user performs interactive operations to generate the configuration file
            console.log(defaultConfigJsonName+"File does not exist. Please follow these instructions.")
            program.version('v' + require('./package.json').version, '-v, --version')
                .action(() = > {
                        inquirer.prompt([
                            {
                                type:'input'.name: 'configPath'.message: 'Please enter LottieConfig file path: (e.g. SRC/LottieConfig. Json)'.validate:val= >{
                                    if (fs.existsSync(val)) {
                                        return true;
                                    }
                                    return 'File does not exist, please enter correct file path'}}, {type:'input'.name: 'outFileName'.message: 'Please input and output the name of the resource file: (e.g. Lottie-assets.js)'}, {type:'input'.name: 'to'.message: 'Please input and output resource file save directory: (for example: dist)'
                            },
                            {
                                type:'input'.name: 'globalName'.message: 'Please enter global access extract resource object: (for example: window._config)'
                            },
                            {
                                type:'rawlist'.message:'Does the image resource generate an absolute path'.name:'absPath'.choices:[
                                    {
                                        key:"yes".name:"Yes".value:1.checked: true // It is selected by default
                                    },
                                    {
                                        key:"no".name:"No." ".value:2,
                                    }
                                ]
                            }


                        ]).then(async(answers)  =>  {
                            extractAssets(answers,() = >{});
                        }).catch((e) = >{
                            console.log(Error message:,e); })}); program.parse(process.argv); }});Copy the code

The next step is how to extract the content of json from the configuration file to generate the image URL.

Here, since lottieconfig. json in the configuration file we read is a network JSON, we need to request the network:

Let’s install Request to request the network

    cnpm install request -D
Copy the code

// Request network code

      /** ** * Request Lottie JSON file *@memberOf LottieExtractAssetsPlugin* /
   function requestLottie(url,isAbsPath){
       return new Promise((resolve,reject) = >{
          request(url,  (error, response, body) = > {
              if(! error && response.statusCode ==200) {
                try{
                  const lottieData=JSON.parse(body);
                  const result= lottieParse(lottieData,url,isAbsPath);
                  resolve(result);
                }catch(e){
                    console.log(e); }}else{
                  reject(url+= = "failure"); }})})}Copy the code

The complete code has been uploaded to Githublottie-extract-Assets

Contracted out NPM

  1. NPM login login

  2. NPM publish Publish upload

Then our toolkit is ready to use.

conclusion

One step at a time, solid work!