preface

In daily project, we often meet with some components do not conform to the requirements of the use of our, meet only need to add a simple/deep/depth to modify the style, but if the component structure does not conform to the requirements or need to add a new HTML element when I was at sea, this article teach everyone how to modify the component library of others, Take the Vant component library as an example

demand

Now I have a request to modify the preview component ImagePreviewItem in Vant and add a Gaussian blur background. The page looks like 👇 :

Demand analysis

The implementation principle is very simple: the foreground image is set to contain, the background image is set to cover, and then add a layer of black transparency mask. The implementation method is as follows: 👇:

<body>
  <div class="container"></div>
  <div class="mat_class">
    <img
      src="Https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1991193171, & FM = 26 & gp = 0. 3776224643 class ="image"
    />
  </div>
  <div class="mask"></div>
</body>
<style>
  body {
    margin: 0;
    padding: 0;
  }
  .container {
    width: 100%;
    height: calc(100vh);
    background: url(https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1991193171-3776224643 & FM the no - repeat; background-size: cover; filter: blur(10px);
  }
  .mat_class {
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    width: calc(100vw);
    z-index: 400;
  }
  .image {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  .mask {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: black;
    z-index: 200;
    opacity: 0.2;
  }
</style>
Copy the code

The preparatory work

Patch-package is a package used to patch other NPM packages. The actual principle is also to save a modified code in this project, except that it saves the result of Git diff instead of the full code, thus saving the code volume

  • The installationpatch-package
npm i patch-package --save-dev
Copy the code
  • Go to thegithubdownloadpackage.jsonThe corresponding version invantComponent source

Began to transform

  1. Open thenode_moduleUnder foldervantFolder, openpackage.jsonFile, you can see
"main": "lib/index.js"."module": "es/index.js".Copy the code

Because we are using ESM specification import here, we use Module

So what needs to be modified is the imagePreviewitem.js file in image-Preview in the es folder under vant

  1. Since es compiles code that is not familiar to us, minor changes are ok, but major changes are very difficult for those who are not familiar with this syntax, which is why we need to download vant source code

Open the vant source file and find the imagePreviewitem.js file in the SRC folder. This is the source of the preview component. Add the fixed style and the new HTML element respectively:

computed: {
+ containStyle: function containStyle() {
+ const style = {
+ background: 'url(' + this.src + ') no-repeat',
+ backgroundSize: 'cover',
+};
+ return style;
+},
   imageStyle() {
...

render() {
  const imageSlots = {
    loading: () => <Loading type="spinner" />,
  };
  return (
    <SwipeItem class={bem('swipe-item')}>
+ 
      
<Image src={this.src} fit="contain" class={bem('image', { vertical: this.vertical })} style={this.imageStyle} scopedSlots={imageSlots} onLoad={this.onLoad} /> +
</SwipeItem> ); }, Copy the code

Then execute YARN Build to the es folder to create the es file in node_module

All you need to do is copy the code snippet to our node_module to change the package source

Next comes the most important step:

  1. performnpx patch-package vanttovantPatch will be currentnode_modulesUnder the source code with the original source codegit diff

The NPM will then create a file named vant+version.patch in the Patches directory under the root of the project, and submit it to Git so that other updates will work as well.

  1. And then just executenpx patch-packageThe command will put the itempatchesThe patch in the directory is applied tonode_modulesIn the corresponding package of, the execution time can generally be set topostinstallThe hook
"scripts": {
  "postinstall": "patch-package"
}
Copy the code
  1. The previous approach applies all the patches to the project. This can be used if you want to apply a separate patch when the package version is updatedgitExecute command:
Git apply - ignore - whitespace patches/package - the name + 0.44.2. PatchCopy the code

use

In this case, we only need to add dynamic styles to the masks, images and backgrounds that we have added, so that the preview effect in other modules will not be affected (because we did not add size and additional styles, so we can keep the original effect).

Full example 🌰 :

<template>
  <div>
    <van-image-preview
      v-model="show"
      :images="images"
      @change="onChange"
      :closeable="true"
    />
    <button @click="preview">preview</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      show: false.index: 0.images: [
        'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1943289212, & FM = 26 & gp = 0. 3608954242 JPG'.'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1991193171, & FM = 26 & gp = 0. 3776224643 JPG',]}; },methods: {
    onChange(index) {
      this.index = index;
    },
    preview() {
      this.show = true; ,}}};</script>
<style lang="less" scoped>
/deep/ .van-image-preview__swipe-mask {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: black;
  z-index: 200;
  opacity: 0.2;
}
/deep/ .van-image-preview__overlay {
  background-color: white;
}
/deep/ .van-image-preview__image {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: calc(100vw);
  z-index: 400;
}
/deep/ .van-image-preview__swipe-container {
  width: 100%;
  height: calc(100vh);
  filter: blur(10px);
}
</style>
Copy the code

episode

I changed the node_module directly, hoping to see the effect immediately, but there is a problem, how to modify the node_module found that it does not take effect

After some reflection, it was found that the dllPlugin plugin cache problem

To eliminate caching, you must run yarn Build: DLL to clear the cache before each change and run the NPX patch-package vant command

Useful tool

Most of the time, we will encounter a variable error in the template template. You can print the result on the console as follows

// Can only be used in test environments
// main.js
Vue.prototype.$log = window.console.log;

// called inside the component
<div>{{$log(info)}}</div>
Copy the code

Summarizes the steps

  1. The installationpatch-packageTo download the corresponding versionvantThe source code
  2. invantSource code modified after compiling, will generateesFolder corresponding code copy tonode_moduleIn the
  3. There aredllPluginTo perform firstyarn build:dllClear the cache, then executenpx patch-package vantgeneratevant+version.patchFile and submit

4. Run the postinstall or git command to apply the patch of the latest version

Extension 🏆

If you find this article helpful, check out my other articles at ❤️ :

👍 “Multigraph alert” those years, the blob abused the programmer monkey wake up!

Introductory notes | fast 🚀 👍 vue3 practical experience

👍 10 simple tips to make your vue.js code more elegant 🍊

👍 Close contact with websocket🚀

👍 5 Design patterns to know for Web development