使用 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

可见导入成功了。

待解决的问题

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