使用 vue cli 4 開發 chrome 插件

想要更好的閱讀體驗,可以轉我的個人博客: nonlinearthink

創建 vue cli 4 項目

創建一個項目

vue create todolist

勾選 BabelTypeScriptCSS Pre-processorsLinter / Formatter

? Please pick a preset: Manually select features
? Check the features needed for your project:
 ◉ Babel
❯◉ TypeScript
 ◯ Progressive Web App (PWA) Support
 ◯ Router
 ◯ Vuex
 ◉ CSS Pre-processors
 ◉ Linter / Formatter
 ◯ Unit Testing
 ◯ E2E Testing

這裏,CSS 預處理器隨意,我選了 Sass/SCSS (with dart-sass)

另外,linter / formatter 中的 TSLint 已經不再維護,建議使用 ESLint + Prettier

{% note warning %}
不要使用 class-style component syntax,見 vue-cli-plugin-chrome-ext
{% endnote %}

添加 chrome-ext 插件

vue add chrome-ext

記得這裏勾選 ts:

? Name of the Chrome Extension? todolist
? Description for the Chrome Extension? chrome extension
? Version for the Chrome Extension? 0.0.1
? javascript or typescript? 
  js 
❯ ts 

出現了一個錯誤:

⠋  Running completion hooks...error: Require statement not part of import statement (@typescript-eslint/no-var-requires) at vue.config.js:1:27:
> 1 | const CopyWebpackPlugin = require("copy-webpack-plugin");
    |                           ^
  2 | const path = require("path");
  3 | 
  4 | // Generate pages object

這是因爲 eslint 不允許 commonjs 的語法,考慮到 vue.config.js 是一個比較特殊的文件,我們應該把它放到 .eslintignore 文件中,讓 eslint 忽略 它。

.eslintignore 中寫入:

vue.config.js

vue-cli-plugin-chrome-ext 創建不是 SPA 應用,chrome 插件有很多界面,所以是每一個界面分別編譯。

比如,src/popup 是一個界面,src/options 也是一個界面。

這樣,原先很多文件都沒用了,我們可以把它們刪掉,分別是 src/main.tssrc/App.vue

熱重載開發

使用 npm run build-watch 可以使用熱重載的方式進行開發。

運行後會生成一個 dist 文件夾,每次你更改代碼都會重新編譯和加載一次。

將 dist 導入到 chrome 插件中

進入 chrome://extensions/,選擇和加載 dist 文件夾進來。

todolist extension

加載成功之後,記得去右上角管理界面開啓 popup 界面 ( 新版本 chrome )。

manage extensions

現在,代碼打完之後就能立馬在 chrome 的 popup 視圖裏看到渲染結果。

使用 UI 組件

雖然 vue 是跑起來了,但是如果不能導入組件,那也沒用。

ant design vue 爲例,我門來測試一下。

npm i --save ant-design-vue

在 popup 界面導入

src/popup/index.ts 中添加以下內容:

import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
Vue.use(Antd);

Vue.config.productionTip = false;

前面我們說過,src文件夾下面的每一個文件夾代表了一個頁面,每個頁面都有對應的 index.ts(相當於main.js)index.htmlApp.vue

也就是說,我們如果要使用UI庫,不是在一個全局的 main.js 裏面配置一遍就好了,我們需要在每一個頁面的文件夾下的 index.ts 中都導入。

這裏我們僅在 popup 界面下導入了,如果你需要在 options 界面中也使用,則需要去 src/options/index.ts 下面一樣導入一遍。

編寫一個簡單的 popup 界面

使用 ant designcard 組件來測試一下,是否可以使用。

界面的主要代碼,應該寫在 App/App.vue 目錄中。

<template>
  <div class="main_app">
    <a-card title="Jaycee Chow">
      a good coder
    </a-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "app"
};
</script>

<style>
.main_app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  height: 500px;
  width: 300px;
  padding: 10px;
}
</style>

效果大概這樣子:

demo

可見導入成功了。

待解決的問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章