Code Monkey home page Code Monkey logo

vitesse-webext's Introduction

WebExtension Vite Starter

A Vite powered WebExtension (Chrome, FireFox, etc.) starter template.

Popup

Options Page

Inject Vue App into the Content Script

Features

  • ⚡️ Instant HMR - use Vite on dev (no more refresh!)
  • 🥝 Vue 3 - Composition API, <script setup> syntax and more!
  • 💬 Effortless communications - powered by webext-bridge and VueUse storage
  • 🌈 UnoCSS - The instant on-demand Atomic CSS engine.
  • 🦾 TypeScript - type safe
  • 📦 Components auto importing
  • 🌟 Icons - Access to icons from any iconset directly
  • 🖥 Content Script - Use Vue even in content script
  • 🌍 WebExtension - isomorphic extension for Chrome, Firefox, and others
  • 📃 Dynamic manifest.json with full type support

Pre-packed

WebExtension Libraries

Vite Plugins

Vue Plugins

  • VueUse - collection of useful composition APIs

UI Frameworks

  • UnoCSS - the instant on-demand Atomic CSS engine

Coding Style

Dev tools

  • TypeScript
  • pnpm - fast, disk space efficient package manager
  • esno - TypeScript / ESNext node runtime powered by esbuild
  • npm-run-all - Run multiple npm-scripts in parallel or sequential
  • web-ext - Streamlined experience for developing web extensions

Use the Template

GitHub Template

Create a repo from this template on GitHub.

Clone to local

If you prefer to do it manually with the cleaner git history

If you don't have pnpm installed, run: npm install -g pnpm

npx degit antfu/vitesse-webext my-webext
cd my-webext
pnpm i

Usage

Folders

  • src - main source.
    • contentScript - scripts and components to be injected as content_script
    • background - scripts for background.
    • components - auto-imported Vue components that are shared in popup and options page.
    • styles - styles shared in popup and options page
    • assets - assets used in Vue components
    • manifest.ts - manifest for the extension.
  • extension - extension package root.
    • assets - static assets (mainly for manifest.json).
    • dist - built files, also serve stub entry for Vite on development.
  • scripts - development and bundling helper scripts.

Development

pnpm dev

Then load extension in browser with the extension/ folder.

For Firefox developers, you can run the following command instead:

pnpm start:firefox

web-ext auto reload the extension when extension/ files changed.

While Vite handles HMR automatically in the most of the case, Extensions Reloader is still recommanded for cleaner hard reloading.

Using Gitpod

If you have a web browser, you can get a fully pre-configured development environment with one click:

Open in Gitpod

Build

To build the extension, run

pnpm build

And then pack files under extension, you can upload extension.crx or extension.xpi to appropriate extension store.

Credits

Volta

This template is originally made for the volta.net browser extension.

Variations

This is a variant of Vitesse, check out the full variations list.

vitesse-webext's People

Contributors

abdullahaleiti avatar andarist avatar antfu avatar atinux avatar birdgg avatar djfhe avatar dongido001 avatar elliot67 avatar hankolsen avatar jsiwa avatar kirklin avatar manutopik avatar ntnyq avatar privatenumber avatar rusenli avatar shaal avatar teppeis avatar tmkx avatar tshemeng avatar wensonsmith avatar wgrzr avatar yingpengsha avatar yunyoujun avatar zgayjjf avatar ziloen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vitesse-webext's Issues

Keep contentScripts individual

Hi,

I find the vitesse-webext project contains only one index.global.js under contentScripts. If I want to keep contentScript individual, what should I do?

There are some build configs in vite.config.content.ts file, but I not so familiar with vite, could you please give me some example?

vue devtools

I can't see the vue devtools panel. I would like to open it for the options page and popup. Is it possible?

How do I use assets correctly?

Hey! When running in dev mode, the following works:

// Component in src/components/
<img src="../../assets/icon.svg" />

... and using any other path here doesn't seem to work.

But then, when running build, I get the following error:

error during build:
Error: Could not resolve '../../assets/icon.svg' from src/components/Tweets.vue
    at error (/Users/user/code/bugle-vue/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:158:30)
    at ModuleLoader.handleResolveId (/Users/user/code/bugle-vue/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:22263:24)
    at /Users/user/code/bugle-vue/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:22257:26
 ELIFECYCLE  Command failed with exit code 1.
ERROR: "build:web" exited with 1.
 ELIFECYCLE  Command failed with exit code 1.

How do I use assets correctly?

branch: refactor/mv3 use tsx

Describe the bug

image

image

image

Reproduction

file path:vitesse-webext/src/popup/Popup.vue

update script lang

<script setup lang="tsx">
import { storageDemo } from '~/logic/storage'

function openOptionsPage() {
  browser.runtime.openOptionsPage()
}
</script>

System Info

System:
    OS: macOS 11.7.1
    CPU: (8) arm64 Apple M1
    Memory: 103.06 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.14.0 - /usr/local/bin/node
    Yarn: 1.22.5 - ~/.yarn/bin/yarn
    npm: 8.3.1 - /usr/local/bin/npm
  Browsers:
    Chrome: 108.0.5359.124
    Edge: 103.0.1264.71
    Firefox: 106.0
    Safari: 14.1.2

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

[issue] - type of 'browser' is any

Hi, there's a problem with browser variable, its type should not be any.

Steps to Reproduce

  1. Clone the project & install dependencies.
  2. Run pnpm dev.
  3. Content of src/auto-imports.d.ts:
declare global {
  const browser: typeof import('webextension-polyfill')['default']
  // ...
}
  1. The type of every browser variable is any.

As it is, it is impossible to make content_script work

Describe the bug

Apparently, unocss is crashing the project and the background and content_script are not working. By commenting on the references to unocss, I can get the project to work

Reproduction

Restart from scratch on firefox

System Info

System:
    OS: macOS 12.6
    CPU: (4) x64 Intel(R) Core(TM) i7-6567U CPU @ 3.30GHz
    Memory: 47.89 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 18.10.0 - /usr/local/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 8.19.2 - /usr/local/bin/npm
  Browsers:
    Brave Browser: 103.1.40.107
    Chrome: 106.0.5249.119
    Firefox: 105.0.3
    Safari: 16.0
    Safari Technology Preview: 16.0

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Why use relative path to assets?

I'm guessing there's a good reason as to why the following code is present:

vite.config.js

export const sharedConfig: UserConfig = {
    ...
    // rewrite assets to use relative path
    {
      name: 'assets-rewrite',
      enforce: 'post',
      apply: 'build',
      transformIndexHtml (html) {
        return html.replace(/"\/assets\//g, '"../assets/')
      }
    }
}

However, this is causing issues with my extension which is trying to create devtools panels. I'm pretty sure this is due to the structure of my panel, which is under src/devtools/panels/index.html, which ends up referencing dist/devtools/assets instead of dist/assets.

Could you please share some information as to why this decision was made? Perhaps throw this rationale in the code via comments so others are made aware of it as well?

Uncaught SyntaxError: Cannot use import statement outside a module

Hi,

I'm getting the error 'Uncaught SyntaxError: Cannot use import statement outside a module' when importing axios in background.ts and could not find the way to fix it.

I also tried add axios in AutoImport configuration like this: 'axios': [['default', 'axios'], as described in unplugin-auto-import documentation, but without success. In this case axios is just undefined.

Could you please give any tip or example how to solve this problem? Any help would be much appreciated.

Why I can't get `browser.downloads` in background.js

In background/main.ts I tried to save some filed on some specified message. And the code snippet

onMessage('save-me', async () => {
  console.log("downloads?", browser.downloads);

  const blob = new Blob(["array of", ' parts of ', "text file"], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  try {
    await browser.downloads.download({
      url, 
      filename: 'test.txt', 
    })
  } catch (error) {
    console.log('saved failed', error);
  }
})

browser.downloads always undefined. Do you know why?

HMR on contentScript not working on Firefox

Description

HMR on content scripts isn't working for me in Firefox with the current setup.

This comment explains that Firefox caches the content script so this hack is necessary (contentScript removal & background script), but interestingly, content script HMR works fine if I remove this hack.

Reproduction

  1. Clone repo and pnpm i
  2. Run npm run dev in one shell
  3. Run npm run start:firefox in another shell
  4. Navigate to random site and open dev console
  5. Add console.log(1) to src/contentScripts/index.ts

Expectation is for 1 to be logged without refreshing the page, but it does not.

Environment

$ npx envinfo --system --binaries --browsers

  System:
    OS: macOS 11.6
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 181.58 MB / 64.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 14.16.1 - ~/.nvm/versions/node/v14.16.1/bin/node
    Yarn: 1.22.11 - ~/.nvm/versions/node/v14.16.1/bin/yarn
    npm: 6.14.12 - ~/.nvm/versions/node/v14.16.1/bin/npm
  Browsers:
    Chrome: 94.0.4606.81
    Firefox: 93.0
    Safari: 15.0

Could it be that Firefox no longer caches in the latest release?

Would you like to add SolidJS to this template?

There is this cool new super efficient and performant reactive framework SolidJS.
As a learning exercise I've updated the MV3 version of this template (from this refactor/mv3 branch) to SolidJS (and also moved to yarn PnP to avoid the gargantuan number of node_modules files though had to replace esno with ts-node due to this). Current results can be checked out in this fork's mv3_pnp_solid branch, seems to be working fine just like the Vue version.

Would you like to add a SolidJS version to this template (though not sure how to best do that in the same repo, as a separate branch?)? Or would you prefer the opinionated part of the Vite Starter Templates to only cover Vue?

Suggestion: can we have a universal extension template

Hey Everyone,

I am suggesting if we can have a universal extension template with options to use (Plain JS, TS, Vue, React, Angular, Svelte etc) through a cli and create a best possible webext template repo with best practices used in creating extensions for cross browser extension development.

I can help with Angular, JS, TS, Svelte templates for WebExt.

What do you all suggest? Is it a good idea?

some problems about branch:refactor/mv3 until 2022/11/22

Describe the bug

some problems about branch:refactor/mv3 until 2022/11/22

I downloaded the latest source code:

❯ npx degit antfu/vitesse-webext#refactor/mv3 antfu@vitesse-webext_mv3_202211

problem 1

there is a ERR_PNPM_FETCH_404 error when using pnpm to install.

❯ pnpm i
Lockfile is up-to-date, resolution step is skipped
Packages: +893
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 WARN  GET https://registry.npmjs.org/@nodelib/fs.scandir/-/@nodelib/fs.scandir-2.1.5.tgz error (ERR_PNPM_FETCH_404). Will retry in 10 seconds. 2 retries left.
 WARN  GET https://registry.npmjs.org/@nodelib/fs.scandir/-/@nodelib/fs.scandir-2.1.5.tgz error (ERR_PNPM_FETCH_404). Will retry in 1 minute. 1 retries left.
 ERR_PNPM_FETCH_404  GET https://registry.npmjs.org/@nodelib/fs.scandir/-/@nodelib/fs.scandir-2.1.5.tgz: Not Found - 404

No authorization header was set for the request.
Progress: resolved 893, reused 891, downloaded 0, added 0

but it's normal if turn to yarn.

problem 2

scripts/client.tsline:12

const socketHost = `localhost:3303`

the socket port is hardcoded, so If the port is set by env variables, the follwoing error would occur:

client.ts:26 
        
       WebSocket connection to 'ws://localhost:3303/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

problem3

HMR is not stable, sometimes the changed reflected immediately, but sometimes, the changes can't be rendered in time. especially when continuously change the code. I haven't found what's the problem is. @tmkx

Reproduction

reproduction

System Info

System:
    OS: Linux 5.15 Ubuntu 20.04.4 LTS (Focal Fossa)
    CPU: (8) x64 Intel Core Processor (Haswell, no TSX, IBRS)
    Memory: 25.33 GB / 31.35 GB
    Container: Yes
    Shell: 5.8 - /usr/bin/zsh
  Binaries:
    Node: 18.12.0 - ~/.nvm/versions/node/v18.12.0/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v18.12.0/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v18.12.0/bin/npm
  Browsers:
    Chrome: 103.0.5060.53
    Firefox: 105.0

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

pnpm install fails

I have installed the template using the following commands:

npx degit antfu/vitesse-webext my-webext
cd my-webext
pnpm i

The pnpm i fails with the following error.

 WARN  GET https://registry.npmjs.org/esbuild-windows-64/download/esbuild-windows-64-0.13.3.tgz error (ERR_PNPM_FETCH_404). Will retry in 10 seconds. 2 retries left.
 WARN  GET https://registry.npmjs.org/esbuild-windows-64/download/esbuild-windows-64-0.13.3.tgz error (ERR_PNPM_FETCH_404). Will retry in 1 minute. 1 retries left.
Progress: resolved 761, reused 758, downloaded 0, added 0, done
 ENOENT  ENOENT: no such file or directory, open 'C:\development\projects\vonster-webext\node_modules\.pnpm\[email protected]\node_modules\esbuild-windows-64\package.json'

I then tried the default Vitesse template, which worked fine.

Crash on Windows when build.watch is enabled

The dev vite server with the default configs from your template causes a crash on Windows 10 randomly or reliably whenever a new folder on the root drive C:\ is created.

It's similar to this closed vite issue or this one, although the culprit isn't the settings passed to chokidar in your scripts/prepare.ts script, but rather these rollup watcher options

build: {
    watch: isDev
      ? {}
      : undefined,

from vite.config.content.ts

If I comment them out, then vite dev doesn't crash when I create a folder on my C:\ drive. Not sure why the {} (which is also the default in rollup) leads to the watcher watching over the whole drive and thus causing the crash and whether this is a template config issue or an upstream bug (with vite or rollup?) or something

Failed to resolve entry for package "webext-bridge".

I added vitest/unit-test support to the base code, but when running the test command yarn test:unit I m getting error:

Error: Failed to resolve entry for package "webext-bridge". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "webext-bridge". The package may have incorrect main/module/exports specified in its package.json.
 ❯ packageEntryFailure node_modules/vite/dist/node/chunks/dep-f5552faa.js:30629:11
 ❯ resolvePackageEntry node_modules/vite/dist/node/chunks/dep-f5552faa.js:30625:9
 ❯ tryNodeResolve node_modules/vite/dist/node/chunks/dep-f5552faa.js:30440:20
 ❯ Context.resolveId node_modules/vite/dist/node/chunks/dep-f5552faa.js:30257:28
 ❯ Object.resolveId node_modules/vite/dist/node/chunks/dep-f5552faa.js:36922:55
 ❯ processTicksAndRejections ../../../../internal/process/task_queues.js:95:5
 ❯ async TransformContext.resolve node_modules/vite/dist/node/chunks/dep-f5552faa.js:36721:23   
 ❯ async normalizeUrl node_modules/vite/dist/node/chunks/dep-f5552faa.js:73701:34
 ❯ async TransformContext.transform node_modules/vite/dist/node/chunks/dep-f5552faa.js:73843:57 
 ❯ async Object.transform node_modules/vite/dist/node/chunks/dep-f5552faa.js:36985:30

Here is the stackblitz link: https://stackblitz.com/edit/github-sratr2

Constant reloading of the extension

I've just started setting up the template, but I've hit an issue of the vite server doing a non-stop reloading, as can be seen below

constant-reload.mp4

The only changes I've done to the template:

  1. Installed pug, tailwindcss, postcss, sass
  2. Remove all instances of windiss
  3. Setup TailwindCSS as per their instructions for Vite
  4. Created my own custom component and then included it in the popup

I can confirm that not loading the component in popup, doesn't resolve in constant reloading. But I have no idea why this would cause it

The component in question looks like this:

<template lang="pug">
button(
  :type='type'
  :class='classes'
  :disabled='disabled'
  @click="$emit('click')"
)
  slot
</template>

<script>
  export default {
    props: {
      type: {
        type: String,
        default: 'button',
      },
      colour: {
        type: String,
        default: 'primary',
      },
      size: {
        type: String,
        default: 'md',
      },
      disabled: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['click'],
    computed: {
      classes() {
        return {
          'btn-primary': this.colour === 'primary',
          'btn-success': this.colour === 'success',
          'btn-secondary': this.colour === 'secondary',
          'btn-info': this.colour === 'info',
          'btn-warn': this.colour === 'warning',
          'btn-danger': this.colour === 'danger',
          'btn-upgrade': this.colour === 'upgrade',
          'btn-xl': this.size === 'xl',
          'btn-lg': this.size === 'lg',
          'btn-md': this.size === 'md',
          'btn-sm': this.size === 'sm',
          'btn-xs': this.size === 'xs',
          disabled: this.disabled,
        };
      },
    },
  };
</script>

<style lang="scss" scoped>
  button {
    @apply inline-flex items-center px-2.5 py-1.5 border border-transparent;
    @apply text-xs font-medium rounded-md shadow-sm w-full flex justify-center;

    @apply focus_outline-none focus_ring-2 focus_ring-offset-2;
  }

  .btn-secondary {
    @apply border-gray-300 bg-white text-gray-700;
    @apply hover_text-gray-500;
    @apply focus_outline-none focus_ring-blue-300;

    @apply dark_bg-gray-400 dark_bg-opacity-20 dark_text-gray-300;
    @apply dark_border-transparent;

    @apply dark_hover_bg-opacity-30 dark_hover_text-gray-200;
    @apply dark_focus_ring-opacity-10 dark_focus_ring-offset-gray-500;
  }

  .btn-primary {
    @apply border-transparent bg-blue-600 text-white;
    @apply hover_bg-blue-500;
    @apply focus_outline-none focus_ring-blue-300;

    @apply dark_bg-blue-600 dark_bg-opacity-30 dark_text-blue-300;
    @apply dark_hover_bg-opacity-40;
    @apply dark_focus_ring-opacity-10 dark_focus_ring-offset-blue-600;
  }

  .btn-success {
    @apply border-transparent bg-el-green text-white;
    @apply hover_bg-el-green-light;
    @apply focus_outline-none focus_ring-green-300;

    @apply dark_bg-green-600 dark_bg-opacity-20 dark_text-green-400;
    @apply dark_hover_bg-green-600 dark_hover_bg-opacity-40;
    @apply dark_focus_ring-opacity-10 dark_focus_ring-offset-green-600;
  }

  .btn-upgrade {
    @apply bg-gradient-to-r from-purple-600 to-blue-600 text-white;
    @apply border-transparent;
    @apply hover_from-purple-500 hover_to-blue-500;

    &:focus {
      @apply outline-none ring-purple-300;
    }
  }

  .btn-info {
    @apply border-transparent bg-gray-500 text-white;
    @apply hover_bg-gray-400;
    @apply focus_outline-none focus_ring-gray-300;

    @apply dark_bg-gray-400 dark_bg-opacity-50 dark_text-gray-300;
    @apply dark_border-transparent;

    @apply dark_hover_bg-opacity-60 dark_hover_text-gray-200;
    @apply dark_focus_ring-opacity-10 dark_focus_ring-offset-gray-400;
  }

  .btn-warn {
    @apply border-transparent bg-yellow-400 text-white;
    @apply hover_bg-yellow-300;
    @apply focus_outline-none focus_ring-yellow-300;

    @apply dark_bg-yellow-500 dark_bg-opacity-20 dark_text-yellow-400;
    @apply dark_border-transparent;

    @apply dark_hover_bg-opacity-40 dark_hover_text-yellow-200;
    @apply dark_focus_ring-opacity-10 dark_focus_ring-offset-yellow-400;
  }

  .btn-danger {
    @apply border-transparent bg-red-600 text-white;
    @apply hover_bg-red-500;
    @apply focus_outline-none focus_ring-red-300;

    @apply dark_bg-opacity-25 dark_text-red-500;
    @apply dark_hover_bg-red-600 dark_hover_bg-opacity-40;
    @apply dark_focus_ring-opacity-10 dark_focus_ring-offset-red-700;
  }

  .disabled {
    @apply opacity-50 cursor-not-allowed;
  }

  .btn-xl {
    @apply px-6 py-3 text-base leading-6;
  }

  .btn-lg {
    @apply px-4 py-2 text-base leading-6;
  }

  .btn-md {
    @apply px-4 py-2 text-sm leading-5;
  }

  .btn-sm {
    @apply px-3 py-2 text-sm leading-4;
  }

  .btn-xs {
    @apply px-2.5 py-1.5 text-xs leading-4;
  }
</style>

Extension page is immediately closed on save HMR

Whenever I save the code and the extension page is automatically updating with HMR, the page is immediately closed after several seconds.

Reproduction

I start the development by pnpm run dev and then pnpm start:firefox. After I save the code on change, the pnpm start:firefox command is also exited after several seconds. There is no error in pnpm run dev command, it still watching for changes.

Is there any solution to this?

Popup shows "Vite server did not start"

Hey,
I created a repo from the template as suggested in the readme file, and tried to run this project locally for the first time.
I ran this project in dev mode, but I have an issue, no matter what I do I see "Vite server did not start" on the extension.
If I'm building the extension (using pnpm build) and then I try to load the extension, I can see the popup as shown in the readme file.
How can I solve it?

Edit:
While inspecting the plugin in Chrome devtools, I got the following error:
image

Thank you

Content scripts in dev mode don't work in Firefox

Great work on this project! But since I mainly develop in FF I thought I would mention that there is an issue specific to FF which works fine in chromium browsers. If dev mode is enabled (HMR) the content scripts don't even load in the page. Build works fine in FF. Without delete manifest.content_scripts the development mode works, but requires the extension to be reloaded manually.

branch:refactor/mv3 Popup shows "Vite server did not start"

Describe the bug

I donwloaded the latest mv3 branch, and then run it:

npx degit antfu/vitesse-webext#refactor/mv3 antfu@vitesse-webext_mv3
❯ npm run dev

> [email protected] dev
> npm run clear && cross-env NODE_ENV=development run-p dev:*


> [email protected] clear
> rimraf extension extension.*


> [email protected] dev:js
> npm run build:js -- --mode development


> [email protected] dev:bg
> tsup --watch ./src


> [email protected] dev:prepare
> esno scripts/prepare.ts


> [email protected] dev:web
> vite

CLI Building entry: {"background/index":"./src/background/index.ts","mv3client":"./scripts/client.ts"}
CLI Using tsconfig: tsconfig.json
CLI tsup v5.12.9
CLI Using tsup config: /home/john/project/testscratch/git-repos/antfu@vitesse-webext_mv3/tsup.config.ts
CLI Running in watch mode
CLI Target: esnext
ESM Build start
ESM ⚡️ Build success in 36ms
ESM extension/dist/mv3client.mjs        52.13 KB
ESM extension/dist/background/index.mjs 162.94 KB
CLI Watching for changes in "./src"
CLI Ignoring changes in "**/{.git,node_modules}/**" | "extension/dist" | "**/extension/**"

> [email protected] build:js
> vite build --config vite.config.content.ts --mode development

build.terserOptions is specified but build.minify is not set to use Terser. Note Vite now defaults to use esbuild for minification. If you still prefer Terser, set build.minify to "terser".

  vite v2.9.15 dev server running at:

  > Local: http://localhost:3303/
  > Network: use `--host` to expose

  ready in 766ms.

vite v2.9.15 building for development...

watching for file changes...

build started...
transforming (12) contentScripts/views/App.vue PRE  write manifest.json
 PRE  stub options
 PRE  stub popup
✓ 21 modules transformed.
../extension/dist/contentScripts/style.css         3.11 KiB / gzip: 1.05 KiB
../extension/dist/contentScripts/index.global.js   96.18 KiB / gzip: 37.06 KiB
../extension/dist/contentScripts/index.global.js.map 702.67 KiB
built in 4854ms.

but the popup page show: Vite server did not start, why ? how to fix it?

Reproduction

reproduction

System Info

System:
    OS: Linux 5.15 Ubuntu 20.04.4 LTS (Focal Fossa)
    CPU: (8) x64 Intel Core Processor (Haswell, no TSX, IBRS)
    Memory: 25.33 GB / 31.35 GB
    Container: Yes
    Shell: 5.8 - /usr/bin/zsh
  Binaries:
    Node: 18.12.0 - ~/.nvm/versions/node/v18.12.0/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v18.12.0/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v18.12.0/bin/npm
  Browsers:
    Chrome: 103.0.5060.53
    Firefox: 105.0

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Manifest v3

Is there a possibility to use the manifest v3 ?

How could I open the popup as a new window ?

Vite doesn't seem to execute when i use

browser.windows.create({
        url: '../popup/index.html',

from my background script, because i get in my new window : Vite server did not start

Compiling content script with many modules is painfully slow

Hello, I'm using vitesse-webext to develop a fairly large browser extension where the majority of the code is in the content script (using React and other libraries like MUI and Framer Motion). However, the build times for my content script have become painfully slow, taking between 10 and 25 seconds per rebuild:

build started...
✓ 11020 modules transformed.
../extension/dist/contentScripts/index.global.js   744.09 KiB / gzip: 230.18 KiB
../extension/dist/contentScripts/index.global.js.map 3180.64 KiB
built in 17941ms.

Most of the time spent building is after it has printed out the "modules transformed" message - it sits there without any output for a considerable amount of time, then prints rendering chunks (1)..., then a half a second later prints out the rest of the output.

Is there any way I can make this build faster?

Suggestion: content-script Support for using vue

Currently for Content Script Using"build:js": "tsup src/background src/content --format iife --out-dir extension/dist --no-splitting" does not support inserting vue components in the page. I think many people have such a scene. Do you think is a good idea?

should use storage.local over window.localStorage

Problem

This template currently uses localStorage(1, 2).

MDN advises against using local storage because of persistence issues:

Although this API is similar to Window.localStorage it is recommended that you don't use Window.localStorage in extension code. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the storage.local API will be correctly persisted in these scenarios.

Proposal

Use storage.local via webextension-polyfill.

FYI VueUse useStorage accepts a 3rd parameter to accept a StoreLike object, so perhaps a wrapper around storage.local could have been passed in. However, storage.local APIs return promises so it cannot.

Because of storage.local's async nature, it might be best to create another composable function that returns an isLoaded state.

LocalStorage is not kept in sync between the `Options`/`Popup` and `contentScripts`

Description

LocalStorage is not kept in sync between the Options/Popup and contentScripts. Only initial value at initialisation is seen at all levels.

Reproduction

  • Clone repo and pnpm i
  • Run pnpm dev
  • Load the extension in the browser
  • Add this line to contentScripts/index.ts after console.info('[vitesse-webext] Hello world from content script')
    • console.info('[vitesse-webext] Storage loaded', JSON.stringify(storageDemo))
    • and importing the storage import { storageDemo } from '~/logic/storage'

From any website, while the web extension is loaded we will see in the browser console

[vitesse-webext] Storage loaded {"_shallow":false,"dep":{"w":0,"n":0},"__v_isRef":true,"_rawValue":"Storage Demo","_value":"Storage Demo"}

that is the storage initiated with value 'Storage Demo' used in `logic/storage.ts'

  • Then try to change this value in the Options page to 'New Storage Value'
  • This value will update the storage in the web extension and keep it reactive between the Options page and Popup. On the other hand the storage value seen from the contentScripts is all the time the initial value given at creation time = 'Storage Demo'

I would guess this local storage is different between the web extension and the page where the contentScripts are injected, but I am curious about why the initial value is properly seen in all the components including the contentScripts.

I can use messages to communicate between the Options/Popup pages and the contentScript but will be great to better understand this behaviour.

Environment

$ npx envinfo --system --binaries --browsers

System:

OS: macOS 11.1
CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Memory: 29.61 MB / 32.00 GB
Shell: 5.8 - /bin/zsh

Binaries:

Node: 16.0.0 - ~/.nvm/versions/node/v16.0.0/bin/node
npm: 7.23.0 - ~/.nvm/versions/node/v16.0.0/bin/npm

Browsers:

Chrome: 96.0.4664.110
Safari: 14.0.2

Does not inject content script into frames in dev mode

I updated my manifest.ts to contain the following:

    content_scripts: [{
      matches: ['http://*/*', 'https://*/*'],
      all_frames: true,
      js: ['./dist/contentScripts/index.global.js'],
    }],

First, when I run npm run dev, I don't see this entry in extension/manifest.json, but that just looks like how the template operates? So maybe that's OK. However, once I update src/contentScripts/index.ts to contain

debugger
if (window !== window.top) {
    console.log('[vitesse-webext] Inside iframe')
}

It hits the debugger once but it doesn't print anything despite the page containing iframes.
I tested this on a codepen.io page.

Is this a known limitation? What am I doing wrong? 🙁

Cannot publish to store because of obfuscated code

Hello, I'm trying to publish my extension built with this great template, however the Chrome store does not help :

Screenshot_20210807-131222.jpg

Is there any workaround ?

I'm using npm run build then zipping the extension folder

Thank you !

No files matching the pattern "'src/**/*.{json,ts,js,vue}'" were found.

I just cloned the project locally and tried cmd pnpm run lint, it throws following error

$ pnpm run lint

> [email protected] lint D:\create-vue
> eslint 'src/**/*.{json,ts,js,vue}'


Oops! Something went wrong! :(

ESLint: 7.32.0

No files matching the pattern "'src/**/*.{json,ts,js,vue}'" were found.
Please check for typing mistakes in the pattern.

 ELIFECYCLE  Command failed with exit code 2.

But in vs-code its showing errors
image

Storage reactivity

Describe the bug

Open the option page and the popup, then try to change storageDemo value in the option page, it should change in the popup in realtime. It's not easy to see because the popup close when you activate the option page. With firefox, you can toggle the Disable popup auto-hide option to see it in action.
It's particularly relevant with the opposite ; changing storageDemo in the popup.

Furthermore, add this in the background :

import { storageDemo } from '~/logic/storage'

watch(storageDemo, (val) => {
  console.log('storageDemo', storageDemo)
}, { immediate: true })

We can see that it's also not reactive in the background.

I know this issue #55, but the background, option page and popup «live» in the same context, not the contentScripts. The storage should be reactive between background, option page and popup.

Edit: I add this code below to the reproduction branch.


You can try with vueuse useStorage by inserting this code in those three parts of the extension :

import { useStorage } from '@vueuse/core'
const localstorageDemo = useStorage('localstorageDemo', 'localstorage')
watch(localstorageDemo, (val) => {
  console.log(val)
}, { immediate: true })

And add an input in the popup to edit the value :

<input v-model="storageDemo" class="border border-gray-400 rounded px-2 py-1 mt-2">

The reactivity works through the local storage reactivity provided by useStorage.

Reproduction

https://github.com/ManUtopiK/vitesse-webext/tree/storageReactivityIssue

System Info

System:
    OS: Linux 5.15 Manjaro Linux
    CPU: (8) x64 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
    Memory: 7.31 GB / 31.14 GB
    Container: Yes
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.3.0 - ~/.nvm/versions/node/v18.3.0/bin/node
    Yarn: 1.22.19 - /usr/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v18.3.0/bin/npm
  Browsers:
    Chromium: 107.0.5304.121
    Firefox: 107.0

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Send message not working from custom html page.

I have just cloned the latest vitesse-webext project and added the following code, which is sending message correctly.

// src/options/Options.vue
<script setup lang="ts">
import { sendMessage, onMessage } from 'webext-bridge'

import { storageDemo } from '~/logic/storage'

const logIt = async() => {
  console.log('hello there')
  const dd = await sendMessage('get-current-tab', {}, 'background')
  console.log(dd)
}
</script>

It logged both console messages when Log it button is clicked.

Now I have another page which I can access at url: chrome-extension://[id-of-extension]/test/index.html, which contains the same code to send message but its failing silently.

// src/test/Options.vue 
<script setup lang="ts">
import { sendMessage, onMessage } from 'webext-bridge'

import { storageDemo } from '~/logic/storage'

const logIt = async() => {
  console.log('hello there')
  const dd = await sendMessage('get-current-tab', {}, 'background')
  console.log(dd)
}
</script>

the complete code can be found at https://stackblitz.com/edit/vitejs-vite-ngk771?file=src%2Ftest%2FOptions.vue&terminal=dev

After pnpm install, it reports an error

Describe the bug

 ERR_STREAM_PREMATURE_CLOSE  Premature close

Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
    at new NodeError (internal/errors.js:322:7)
    at IncomingMessage.onclose (internal/streams/end-of-stream.js:117:38)
    at IncomingMessage.emit (events.js:400:28)
    at TLSSocket.socketCloseListener (_http_client.js:432:11)
    at TLSSocket.emit (events.js:412:35)
    at net.js:686:12
    at TCP.done (_tls_wrap.js:564:7)

Reproduction

null

System Info

MacOS 
Chrome 
`pnpm install`

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

升级依赖后,事件相关会报ts错误

Describe the bug

@keydown="(e: KeyboardEvent) => {
                if (e.key === 'Enter') {
                  so()
                }
              }"

不能将类型“(e: KeyboardEvent) => void”分配给类型“KeyboardEvent”。ts(2322)
__VLS_types.ts(107, 56): 所需类型来自属性 "keydown",在此处的 "EventObject<undefined, "keydown", {}, KeyboardEvent | undefined>" 类型上声明该属性

@click="so()"

不能将类型“($event: any) => void”分配给类型“MouseEvent”。ts(2322)
__VLS_types.ts(107, 56): 所需类型来自属性 "click",在此处的 "EventObject<undefined, "click", {}, MouseEvent | undefined>" 类型上声明该属性

<Field v-slot="{ handleChange, value }" name="password">
          <input :value="value" name="password" type="password" class="mt-4 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-sm border-gray-300 border rounded-md p-3" @input="handleChange">
        </Field>

不能将类型“(e: unknown, shouldValidate?: boolean | undefined) => void”分配给类型“Event”。ts(2322)
__VLS_types.ts(107, 56): 所需类型来自属性 "input",在此处的 "EventObject<undefined, "input", {}, Event | undefined>" 类型上声明该属性

package.json

{
  "name": "vitesse-webext",
  "displayName": "Vitesse WebExt",
  "version": "0.0.1",
  "private": true,
  "packageManager": "[email protected]",
  "description": "[description]",
  "scripts": {
    "dev": "npm run clear && cross-env NODE_ENV=development run-p dev:*",
    "dev:prepare": "esno scripts/prepare.ts",
    "dev:web": "vite",
    "dev:js": "npm run build:js -- --mode development",
    "build": "cross-env NODE_ENV=production run-s clear build:web build:prepare build:js",
    "build:prepare": "esno scripts/prepare.ts",
    "build:web": "vite build",
    "build:js": "vite build --config vite.config.content.ts",
    "pack": "cross-env NODE_ENV=production run-p pack:*",
    "pack:zip": "rimraf extension.zip && jszip-cli add extension/* -o ./extension.zip",
    "pack:crx": "crx pack extension -o ./extension.crx",
    "pack:xpi": "cross-env WEB_EXT_ARTIFACTS_DIR=./ web-ext build --source-dir ./extension --filename extension.xpi --overwrite-dest",
    "start:chromium": "web-ext run --source-dir ./extension --target=chromium",
    "start:firefox": "web-ext run --source-dir ./extension --target=firefox-desktop",
    "clear": "rimraf extension/dist extension/manifest.json extension.*",
    "lint": "eslint .",
    "test": "vitest test"
  },
  "dependencies": {
    "crypto-js": "^4.1.1",
    "element-plus": "^2.2.17",
    "ohmyfetch": "^0.4.19",
    "vee-validate": "^4.6.10",
    "vuedraggable": "^4.1.0",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "@antfu/eslint-config": "^0.27.0",
    "@ffflorian/jszip-cli": "^3.1.6",
    "@iconify/json": "^2.1.119",
    "@types/chrome": "^0.0.197",
    "@types/crypto-js": "^4.1.1",
    "@types/fs-extra": "^9.0.13",
    "@types/node": "^18.8.4",
    "@types/webextension-polyfill": "^0.9.1",
    "@typescript-eslint/eslint-plugin": "^5.40.0",
    "@unocss/reset": "^0.45.29",
    "@vitejs/plugin-vue": "^3.1.2",
    "@vue/compiler-sfc": "^3.2.40",
    "@vue/test-utils": "^2.1.0",
    "@vueuse/core": "^9.3.0",
    "chokidar": "^3.5.3",
    "cross-env": "^7.0.3",
    "crx": "^5.0.1",
    "eslint": "^8.25.0",
    "esno": "^0.16.3",
    "fs-extra": "^10.1.0",
    "jsdom": "^20.0.1",
    "kolorist": "^1.6.0",
    "npm-run-all": "^4.1.5",
    "rimraf": "^3.0.2",
    "typescript": "^4.8.4",
    "unocss": "^0.45.29",
    "unplugin-auto-import": "^0.11.2",
    "unplugin-icons": "^0.14.11",
    "unplugin-vue-components": "^0.22.8",
    "vite": "^3.1.7",
    "vitest": "^0.24.1",
    "vue": "^3.2.40",
    "vue-demi": "^0.13.11",
    "web-ext": "^7.2.0",
    "webext-bridge": "^5.0.5",
    "webextension-polyfill": "^0.10.0"
  }
}

Reproduction

System Info

vscode: 版本: 1.72.0
vscode插件
TypeScript Vue Plugin (Volar):v1.0.3
Vue Language Features (Volar):v1.0.3

System:
    OS: macOS 12.5.1
    CPU: (12) x64 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
    Memory: 198.71 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.14.2 - ~/.nvm/versions/node/v16.14.2/bin/node
    Yarn: 1.22.18 - ~/.nvm/versions/node/v16.14.2/bin/yarn
    npm: 8.5.0 - ~/.nvm/versions/node/v16.14.2/bin/npm
  Browsers:
    Chrome: 106.0.5249.103
    Safari: 15.6.1

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Can't Inject Vue App into the Content Script

Describe the bug

Hi, the contentScripts inject not work when I checkout branch to refactor/mv3. But it works when I checkout branch to main.
is anyone can help me? This question has been bothering me for a long time, thank you very much.

Reproduction

Create a repo from this template on GitHub. Clone project. checkout branch refactor/mv3. Delete pnpm-lock.yaml file. Enter pnpm i. Enter pnpm dev

System Info

System:
    OS: macOS 11.4
    CPU: (8) x64 Apple M1
    Memory: 15.56 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node
    Yarn: 1.22.18 - /usr/local/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v16.16.0/bin/npm
  Browsers:
    Chrome: 105.0.5195.102
    Firefox: 96.0
    Safari: 14.1.1

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

process is not defined in content script

Describe the bug

The build is successful, everything works fine except for the content script.
However, it shows an error Uncaught ReferenceError: process is not defined on development mode running pnpm run dev.

Here's the stack trace on the page of the built extension.

image

Reproduction

Build the newly cloned repo and check the content script

System Info

System:
    OS: Linux 5.15 Ubuntu 20.04.5 LTS (Focal Fossa)
    CPU: (4) x64 Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
    Memory: 3.52 GB / 7.66 GB
    Container: Yes
    Shell: 5.8 - /usr/bin/zsh
  Binaries:
    Node: 14.17.0 - ~/.nvm/versions/node/v14.17.0/bin/node
    npm: 6.14.13 - ~/.nvm/versions/node/v14.17.0/bin/npm
  Browsers:
    Brave Browser: 106.1.44.112
    Chrome: 106.0.5249.119
    Firefox: 105.0

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.