If there is a miracle in life, it must be the path of hard work!

preface

Hello, everyone. I am Koba, an ordinary front-end development engineer who is unwilling to be ordinary

Some time ago, Kohane reviewed the webpack related knowledge, and then suddenly found that he seems to have not written webpack plug-in, the hand is a little itching, want to start a webpack plug-in out of play.

While Kohane was racking his brains to write a plugin to play around with, one of the front end user groups was discussing the CDN and jsdelivr’s failure some time ago. Well, isn’t that just right? I gave it a webpack add-on that collects the wool from Jsdelivr for future use. Look, it’s a great idea

Therefore, this article also focuses on the WebPack plug-in.

You may learn the following from this article:

  • github+jsdelivrUse the free CDN
  • Write a simpleWebpack plug-in(I’m not afraid of being asked about webpack anymore!!)
  • usinggithub apiUpload/modify files
  • usinghtml-webpack-pluginModify the content of the output file
  • jsdelivrHang outDegradation Solution
  • usinggithub-jsdelivr-uploadUse CDN directly

1. How to use free CDN?

If you want to use CDN for free, you need to know how to use Jsdelivr

Jsdelivr is accelerated through NPM, Github, and wordpress.

For now, we’ll focus on github.

Using Github, we can accelerate by version or directly using the path.

The difference between the two is that the version will lock the file, whereas if you use the path directly it will change as your file changes.

Emmm, since it is using github way, let’s create a repository first.

Ps:

Start a New Github account,

Start a New Github account

Start a New Github account

It’s so important that it should be repeated for three times.

The plugin will use github’s token, and users with that token will be able to do all sorts of things with your repository.

Remember to set the repository to public at creation time so that JsDelivr can read our github files and add a Readme File. This is to add a readme.md file to our warehouse by default, so that we can test jsdelivr.

Ok, now that the repository is set up, let’s test if we can read our readme.md file through jsdelivr

I’m just going to go through the path.

You can then see that the newly created readme.md can be read normally.

The parameters in the jsdelivr link are shown below.

2. Use the CDN for free via github-jsdelivr-upload

In this case, Koha is going straight to the koha Live Platform, an open source project based on vue-CLI. (Vue and React work properly, which is a webpack plugin.)

The first step in using an NPM package is to review the documentation.

Emmm, and found that we had two issues to deal with, otherwise we might not be able to use the plug-in.

  • vue-cliIn the project createdhtml-webpack-pluginAn earlier version is3.xversion
  • The need for agithub token

The first problem is relatively simple, webpack in the live broadcast platform is 4.x version, so you can directly upgrade the version of HTML-webpack-plugin

NPM I [email protected]Copy the code

How to obtain the github token?

Just follow the pictures below and save the generated token as it will not be displayed after closing

Again, this token can be used to modify your personal warehouse, so in order to avoid the leakage of token may cause unnecessary losses. Create a New Github account.

All right, we’re all set. Let’s start with github-jsdelivr-upload.

First installation

npm i github-jsdelivr-upload
Copy the code

Then according to the documentation in NPM, the corresponding configuration is carried out in vue.config.js

Note that vue-CLI created projects need to manually introduce the HTml-webpack-plugin here, otherwise the default htML-wepback-plugin3.x version will be used.

Then NPM runs build. Take a look at our packing results and format them.

Emmm, you can find that all our links are replaced with links under the domain name JsdeliVR, which is nice, indicating that our CDN plug-in has taken effect.

Github-jsdelivr-upload allows you to create a github-jsdelivr-upload plugin for webpcak. If you want to create a github-jsdelivr-upload plugin for webpcak, you can use github-jsdelivr-upload

3. Write a simple WebPack plug-in

Let’s start by writing the simplest webPack plug-in.

Create myWebPackplugin.js in the following directory:

class MyPlugin {
  constructor(data) {
    const {
      name,
    } = data;
    this.name = name
    this.pluginName = 'MyPlugin'
  }

  apply(compiler) {
    compiler.hooks.emit.tap(this.pluginName, () = > {
      console.log("This is Koha's personal Webpack plugin.")
      console.log("this.name".this.name)
    })
  }
}
module.exports = MyPlugin
Copy the code

Then import the plugin in vue.config.js and then NPM run build

At this point we will find that our console outputs what we wrote in the plug-in

There you have it, a simple plug-in.

A complex plug-in simply calls the appropriate Compiler and complation hooks at the appropriate time, and then performs the corresponding operations.

4. Upload or modify files using the Github API

Do you still remember how we usually push our files to Github?

git add *
git commit -m 'xxx'
git push origin master
Copy the code

It’s usually done on the command line or using visual tools, right?

Github-jsdelivr-upload works the same way.

Emmm, koha did think about it at first, because the logic is the simplest, just add a command line NPM package. But there are some problems with that. For example, all of our packaged machines must have github repository to allow submission of keys, which is not very convenient.

So Koha went out of her way to see if she could upload the files directly to Github. Github does have an API that allows you to upload. These interfaces require github tokens. This is why Github jsdelivr-upload requires a Github token.

upload(path, content, message = 'update cdn') {
    return this.octokit.request('PUT /repos/{owner}/{repo}/contents/{path}', {
      owner: this.owner,
      repo: this.repo,
      path,
      message,
      content
    }).catch(err= > {
      console.log(JSON.parse(JSON.stringify(err)))
    })
  }
Copy the code

5. Modify the output file content using htML-webpack-plugin

Remember that we used the github-jsdelivr-upload plugin in section 2. The plugin will then automatically replace the file path with the one in Jsdelivr. Emmm, how is this handled?

Here we use the getHooks method provided by the HTML-webpack-plugin to get the content in THE HTML and modify it.

The pseudocode is as follows:

compiler.hooks.compilation.tap(this.pluginName, (compilation) = > {
      HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(this.pluginName, async (data, cb) => {
        const assets = getAssets(compilation) // Get the file path
        const cdnUrl = `The ${this.baseCdnUrl}/The ${this.owner}/The ${this.repo}The ${this.cdnType === 'staticaly'?'/main':' '}/The ${this.basePath}`
        const newAssetJson = ['/']
        for(let i in assets){
          for(let item of assets[i]){
            // Re replaces the corresponding file path
          }
        }
        data.plugin.assetJson = newAssetJson
        cb(null, data)
      })
    })
Copy the code

6. Downgrade solution for jsdeliVR failure

Emmm, some time ago jsdelivr went down in a big part of the country. Many people who use Jsdelivr suffer.

Since we wrote such a wool pulling plugin, then we also need to consider this situation

The script and link tags raise an onError event when the file is not loaded correctly.

Ok, so let’s use this onError event to do something.

Encapsulate an errorCDN method, adding data-CDN and errorCDN methods along with all replacement links to jsdeliVR.

The errorCDN method will be triggered when our Jsdelivr file fails to load, and the errorCDN will replace the tag of our loading exception with the local path (deployed server), which is degraded to using the local file.

At this time our page will only appear file loading error, but it will not affect the operation of our page.

function errorCDN(e) {
    var target = e.getAttribute("data-cdn");
    var tagName = e.tagName
    var cdnDOM = document.createElement(tagName);
    if(tagName === 'SCRIPT'){
        cdnDOM.src = ". /" + target;
    }else{
        cdnDOM.href = ". /" + target;
    }
    document.head.appendChild(cdnDOM);
    e.remove();
}
Copy the code

After the language

In this article koha shares how to use the free CDN, briefly analyzes the principle of github jsDelivr-upload webpack, and discusses how Github jsDelivr-upload demotes jsDelivr-upload when jsDelivr-upload fails.

If you feel good after reading this article, you can like it and follow it

If you want to exchange technology with Kohane, you can add wx, and kohane recently set up a technology exchange group (there are many big guys in the group oh ~), you can scan the code to enter the group, hehe ~

Ps: This article is original, reprint please indicate the source.

Github -jsdelivr-upload

NPM links: www.npmjs.com/package/git…

GitHub link: github.com/sulgweb/git…

If possible, please add a star to Kohane’s Github