從零開始寫一個vuepress插件

初始化插件項目

  1. 在任意目錄新建一個插件目錄,我這裏在 /pkg/vuepress-plugin-simple-encrypt

    mkdir /pkg/vuepress-plugin-simple-encrypt
    

    image-20220424215029271

  2. 進入該目錄,初始化項目

    yarn init
    

    輸入插件名 vuepress-plugin-simple-encrypt ,入口文件名 index.js ,其他選項對應填寫即可。

    image-20220424215319909

    初始化之後,package.json 的文件內容:

    {
      "name": "vuepress-plugin-simple-encrypt",
      "version": "1.0.0",
      "description": "a simple encrypt and decrypt for vuepress",
      "main": "index.js",
      "scripts": {
        "test": "yarn test"
      },
      "repository": {
        "type": "git",
        "url": "git+https://github.com/terwer/vuepress-plugin-simple-encrypt.git"
      },
      "keywords": [
        "encrypt",
        "decrypt",
        "vuepress"
      ],
      "author": "terwer",
      "license": "MIT",
      "bugs": {
        "url": "https://github.com/terwer/vuepress-plugin-simple-encrypt/issues"
      },
      "homepage": "https://github.com/terwer/vuepress-plugin-simple-encrypt#readme"
    }
    
  3. 編寫入口文件 index.js

    module.exports = (options, ctx) => {
        return {
            name: 'vuepress-plugin-simple-encrypt',
            async ready() {
                console.log('Hello World!');
            }
        }
    }
    
  4. 注入插件到 vuepress。在 config.ts 文件的插件節點加上我們的插件,注意使用相對目錄目錄

    [
      require('../../pkg/vuepress-plugin-simple-encrypt'), // 主要用於文章部分加密
      {
      }
    ]
    
  5. 啓動項目 yarn dev ,正常情況可以看到輸出 Hello World

image-20220424215853496

插件高級開發

添加插件配置

config.ts 修改插件對應配置如下

[
  require('../../pkg/vuepress-plugin-simple-encrypt'), // 主要用於文章部分加密
  {
    contentTitle: '加密內容',
    unencryptedText: '未加密內容',
    encryptedText: '該內容已加密,如需訪問,請留言或者聯繫 [email protected] 獲取密碼。',
    decryptedText: '文章已成功解密。',
    decryptButtonText: '查看',
    decryptFailText: '密碼錯誤!',
    unencryptedIcon: undefined,
    encryptedIcon: undefined,
    decryptedIcon: undefined
  }
]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章