Giter VIP home page Giter VIP logo

webextension-toolbox / webpack-webextension-plugin Goto Github PK

View Code? Open in Web Editor NEW
79.0 79.0 21.0 1.37 MB

Webpack plugin that compiles WebExtension manifest.json files and adds smart auto reload

Home Page: https://www.npmjs.com/package/@webextension-toolbox/webpack-webextension-plugin

License: Other

JavaScript 6.66% TypeScript 93.34%
autoreload firefox webextension webpack webpack-plugin websockets

webpack-webextension-plugin's Introduction

WebExtension Toolbox

npm version Node.js CI license

Small cli toolbox for creating cross-browser WebExtensions.

If you want to get started quickly check out the yeoman generator for this project.

Browser Support

Official

These browsers are tested through github actions

  • Edge (edge)
  • Firefox (firefox)
  • Chrome (chrome)
  • Safari (safari)
  • Opera (opera)

Unofficial

These browsers will compile but are not tested

  • Internet Explorer (ie)
  • iOS Safari (ios_saf)
  • Opera Mini (op_mini)
  • Android Browser (android)
  • Blackberry Browser (bb)
  • Opera Mobile (op_mob)
  • Chrome for Android (and_chr)
  • Firefox for Android (and_ff)
  • Internet Explorer Mobile (ie_mob)
  • UC Browser (and_uc)
  • Samsung Internet (samsung)
  • QQ Browser (and_qq)
  • Baidu Browser (baidu)
  • KaiOS (kaios)

Features

Packing

The build task creates specific bundles for:

  • Firefox (.xpi)
  • Opera (.crx)

all other bundles are .zip files

Manifest validation

Validates your manifest.json while compiling.

You can skip this by adding --validateManifest to your build or dev command.

Manifest defaults

Uses default fields (name, version, description) from your package.json

Typescript Support

Native typescript support (but not enforced!) (see section How do I use Typescript?)

Manifest vendor keys

Allows you to define vendor specific manifest keys.

Example

manifest.json

"name": "my-extension",
"__chrome__key": "yourchromekey",
"__chrome|opera__key2": "yourblinkkey"

If the vendor is chrome it compiles to:

"name": "my-extension",
"key": "yourchromekey",
"key2": "yourblinkkey"

If the vendor is opera it compiles to:

"name": "my-extension",
"key2": "yourblinkkey"

else it compiles to:

"name": "my-extension"

Polyfill

The WebExtension specification is currently supported on Chrome, Firefox, Edge (Chromium) and Safari (Safari Web Extension’s Browser Compatibility).

This toolbox no longer provides any polyfills for cross-browser support. If you need polyfills e.g. between 'browser' and 'chrome', we recommend detecting the browser during the build time using process.env.VENDOR.

This toolbox comes with babel-preset-env. Feel free add custom configuration if you need any custom polyfills.

Usage

Install

Globally

$ npm install -g @webextension-toolbox/webextension-toolbox

Locally

$ npm install -D @webextension-toolbox/webextension-toolbox

Development

  • Compiles the extension via webpack to dist/<vendor>.
  • Watches all extension files and recompiles on demand.
  • Reloads extension or extension page as soon something changed.
  • Sets process.env.NODE_ENV to development.
  • Sets process.env.VENDOR to the current vendor.

Syntax

$ webextension-toolbox dev <vendor> [..options]

Examples

$ webextension-toolbox dev --help
$ webextension-toolbox dev chrome
$ webextension-toolbox dev firefox
$ webextension-toolbox dev edge
$ webextension-toolbox dev safari

Build

  • Compile extension via webpack to dist/<vendor>.
  • Minifies extension Code.
  • Sets process.env.NODE_ENV to production.
  • Sets process.env.VENDOR to the current vendor.
  • Packs extension to packages.

Syntax

Building

Usage: build [options] <vendor>

Compiles extension for production

Options:
  --swc                                Use SWC instead of Babel
  -c, --config [config]                specify config file path
  -s, --src [src]                      specify source directory (default: "app")
  -t, --target [target]                specify target directory (default: "dist/[vendor]")
  -d, --devtool [string | false]       controls if and how source maps are generated (default: "cheap-source-map")
  --vendor-version [vendorVersion]     last supported vendor (default: current)
  --copy-ignore [copyIgnore...]        Do not copy the files in this list, glob pattern
  --compile-ignore [compileIgnore...]  Do not compile the files in this list, glob pattern
  --no-manifest-validation             Skip Manifest Validation
  --save                               Save config to .webextensiontoolboxrc
  --verbose                            print messages at the beginning and end of incremental build
  --no-minimize                        disables code minification
  -h, --help                           display help for command

Developing

Usage: dev [options] <vendor>

Compiles extension in devmode

Arguments:
  vendor                                The Vendor to compile

Options:
  --swc                                Use SWC instead of Babel
  -c, --config [config]                specify config file path
  -s, --src [src]                      specify source directory (default: "app")
  -t, --target [target]                specify target directory (default: "dist/[vendor]")
  -d, --devtool [string | false]       controls if and how source maps are generated (default: "cheap-source-map")
  --vendor-version [vendorVersion]     last supported vendor (default: current)
  --copy-ignore [copyIgnore...]        Do not copy the files in this list, glob pattern
  --compile-ignore [compileIgnore...]  Do not compile the files in this list, glob pattern
  --no-manifest-validation             Skip Manifest Validation
  --save                               Save config to .webextensiontoolboxrc
  --verbose                            print messages at the beginning and end of incremental build
  --no-auto-reload                     Do not inject auto reload scripts into background pages or service workers
  -p, --port [port]                    Define the port for the websocket development server (default: "35729")
  --dev-server [devServer]             use webpack dev server to serve bundled files (default: false)
  -h, --help                           display help for command

.webextensiontoolboxrc

This file is used to configure the WebExtension Toolbox without cli options. You can generate it by running webextension-toolbox <options> --save command. This will take your current cli options and save them to .webextensiontoolboxrc. You can then run webextension-toolbox without any options

Customizing webpack config

In order to extend the usage of webpack, you can define a function that extends its config through a file you define through the usage of the -c option in your project root.

module.exports = {
  webpack: (config, { dev, vendor }) => {
    // Perform customizations to webpack config

    // Important: return the modified config
    return config;
  },
};

As WebExtension Toolbox uses webpack’s devtool feature under the hood, you can also customize the desired devtool with the --devtool argument.

For example, if you have problems with source maps on Firefox, you can try the following command:

webextension-toolbox build firefox --devtool=inline-cheap-source-map

Please see Issue #58 for more information on this

FAQ

What is the difference to web-ext?

If want to develop browser extensions for Firefox only web-ext might be a better fit for you, since it supports extension signing, better manifest validation and auto mounting.

Nevertheless if you want to develop cross browser extensions using

  • the same development experience in every browser
  • a single codebase
  • custom webpack configuration

webextension-toolbox might be your tool of choice.

How do I use React?

  1. npm install @babel/preset-react --save-dev
  2. Create a .babelrc file next to your package.json file and insert the following contents:
{
  "presets": [
    "@babel/preset-react"
  ]
}

How do I use Typescript?

  1. npm install typescript --save-dev
  2. Run tsc --init or manually add a tsconfig.json file to your project root

What is SWC?

SWC (stands for Speedy Web Compiler) is a super-fast TypeScript / JavaScript compiler written in Rust. It's an alternative to Babel. For more informaiton see: https://github.com/swc-project/swc

License

Copyright 2018-2023 Henrik Wenz

This project is free software released under the MIT license.

webpack-webextension-plugin's People

Contributors

balcsida avatar dependabot-preview[bot] avatar dependabot[bot] avatar erictrinh avatar ermik avatar evhaus avatar fchastanet avatar fregante avatar greenkeeper[bot] avatar handtrix avatar here-nerd avatar platy avatar renovate-bot avatar robinvdbroeck avatar rthaut avatar tm1000 avatar vwheezy 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

Watchers

 avatar  avatar  avatar

webpack-webextension-plugin's Issues

Can't connect to WS server via WSL 2

I'm running the extension from WSL2 Ubuntu on windows 10. I just can't seem to get the auto-reloading to work because of the connectivity issue. Everything else works fine.. my APIs which are also inside WSL2 connect perfectly fine via localhost.

Screenshot 2021-04-28 122620

I also tried the server host to 0.0.0.0 but it changed nothing.

Any help is appreciated.

Docs on usage not working

The docs on Usage did not work in my setup. I was getting a TypeError: saying WebextensionPlugin is not a constructor. I had to replace it with the following:

import { WebextensionPlugin } from "@webextension-toolbox/webpack-webextension-plugin";

const config = {
  plugins: [
    new WebextensionPlugin({
      vendor: "chrome",
    }),
  ],
};

I can submit a PR for this, but I'm not sure if this is the correct behavior or if my setup had to do with the issue.

Deprecation warning with Webpack 5.28.0

Upgrading our setup to Webpack 5.28.0 yields this warning:

(node:12778) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
	Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
	Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
    at WebextensionPlugin.addManifest (.../node_modules/webpack-webextension-plugin/index.js:211:41)
    at async Promise.all (index 1)

Note: running node --trace-deprecation ./node_modules/webpack/bin/webpack.js to provide a stack trace.

It correspond to this code line.

Repeated file changes doesn't properly compile manifest

Using a mostly standard setup, the first dev compile outputs the correct manifest.json but every reload after uses the non-compiled version.

E.g. first compilation outputs:

manifest.json
{
  "name": "__MSG_appName__",
  "description": "__MSG_appDescription__",
  "version": "1.0.0",
  "short_name": "__MSG_appShortName__",
  "manifest_version": 3,
  "default_locale": "en",
  "background": {
    "scripts": [
      "serviceWorker.js",
      "webextension-toolbox/background_page.js"
    ]
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "contentScript.js"
      ]
    }
  ],
  "permissions": [
    "storage",
    "scripting"
  ],
  "options_ui": {
    "page": "pages/options.html",
    "open_in_tab": true
  },
  "action": {
    "default_title": "__MSG_browserActionTitle__",
    "default_popup": "pages/popup.html",
    "default_icon": {
      "16": "images/icon-16x.png",
      "32": "images/icon-32x.png",
      "48": "images/icon-48x.png",
      "128": "images/icon-128x.png"
    }
  },
  "icons": {
    "16": "images/icon-16x.png",
    "32": "images/images-32x.png",
    "48": "images/icon-48x.png",
    "128": "images/icon-128x.png"
  },
  "browser_specific_settings": {
    "gecko": {
      "id": "[email protected]"
    }
  }
}

Second compilation:

manifest.json
{
  "name": "__MSG_appName__",
  "short_name": "__MSG_appShortName__",
  "description": "__MSG_appDescription__",
  "manifest_version": 3,
  "default_locale": "en",
  "background": {
    "scripts": ["serviceWorker.js"]
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["contentScript.js"]
    }
  ],
  "permissions": ["storage", "scripting"],
  "options_ui": {
    "page": "pages/options.html",
    "open_in_tab": true
  },
  "action": {
    "default_title": "__MSG_browserActionTitle__",
    "default_popup": "pages/popup.html",
    "default_icon": {
      "16": "images/icon-16x.png",
      "32": "images/icon-32x.png",
      "48": "images/icon-48x.png",
      "128": "images/icon-128x.png"
    }
  },
  "icons": {
    "16": "images/icon-16x.png",
    "32": "images/images-32x.png",
    "48": "images/icon-48x.png",
    "128": "images/icon-128x.png"
  },
  "__firefox|safari__browser_specific_settings": {
    "gecko": {
      "id": "[email protected]"
    }
  }
}

First compile output shows:

asset manifest.json 1.08 KiB [emitted]

Second compile output shows:

asset manifest.json 997 bytes [emitted] [from: manifest.json] [copied]

I've outputted the changedFiles variables and it's everything in the source tree excluding dist, but including manifest.json for some reason.

Tried using --copy-ignore but couldn't figure out how to inject "packages" with globs.

If this is a code issue, I could help submit a PR. If this is a setup issue, any help would be greatly appreciated!

support webpack 5

Hello,

I'm using webpack 5, I have this error

[webpack-cli] TypeError: Cannot read property 'entries' of undefined
    at WebextensionPlugin.extractChangedFiles (C:\projects\ck_ip_browser_extension\node_modules\webpack-webextension-plugin\index.js:246:57)
    at WebextensionPlugin.reloadExtensions (C:\projects\ck_ip_browser_extension\node_modules\webpack-webextension-plugin\index.js:226:31)
    at WebextensionPlugin.done (C:\projects\ck_ip_browser_extension\node_modules\webpack-webextension-plugin\index.js:98:10)
    at Hook.eval [as callAsync] (eval at create (C:\projects\ck_ip_browser_extension\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:26:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\projects\ck_ip_browser_extension\node_modules\tapable\lib\Hook.js:18:14)
    at Watching._done (C:\projects\ck_ip_browser_extension\node_modules\webpack\lib\Watching.js:260:28)
    at C:\projects\ck_ip_browser_extension\node_modules\webpack\lib\Watching.js:183:21
    at Compiler.emitRecords (C:\projects\ck_ip_browser_extension\node_modules\webpack\lib\Compiler.js:864:39)
    at C:\projects\ck_ip_browser_extension\node_modules\webpack\lib\Watching.js:161:22
    at C:\projects\ck_ip_browser_extension\node_modules\webpack\lib\Compiler.js:846:14

from this doc I found that
Compilation.fileTimestamps and contextTimestamps removed
MIGRATION: Use Compilation.fileSystemInfo instead

Manifest.json custom path

Hi! Thank for the great job that has been done here.

I have a question though, is there a way to define a custom path to the manifest.json file?

Since I'm not very use to work with webpack and related tools, I might be missing something. But, as far as I understand, the plugin will always look for the manifest in options.context path. Maybe an additional option to set the manifest path could do the job? With a fallback to the default one.

update dependencies

this package depends on joi version ^13.3.0 which depends on hoek version 5.x.x which has been deleted for security reasons. therefore I think this package needs to update joi package to its latest version.

I could make a PR but I am not sure how to test these changes.

Is it possible to set the content scripts file name?

Ideally I would like to have the content hash as part of the file name for the scripts '[contenthash]-[name].js', but I don't see anything about this accepting webpack output config, paths, or names, or accepting webpack template strings.

Is this possible, or does the script name have to be something that is predetermined?

Not working with [email protected]

webpack-webextension-plugin listens on ws://localhost:35729
[webpack-cli] TypeError: fileSystemInfo._fileTimestamps.entries is not a function
    at WebextensionPlugin.extractChangedFiles (***\node_modules\webpack-webextension-plugin\index.js:245:48)
    at WebextensionPlugin.reloadExtensions (***\node_modules\webpack-webextension-plugin\index.js:226:31)
    at WebextensionPlugin.done (***\node_modules\webpack-webextension-plugin\index.js:98:10)
    at Hook.eval [as callAsync] (eval at create (***\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:9:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (***\node_modules\tapable\lib\Hook.js:18:14)
    at Watching._done (***\node_modules\webpack\lib\Watching.js:273:28)
    at ***\node_modules\webpack\lib\Watching.js:195:21
    at Compiler.emitRecords (***\node_modules\webpack\lib\Compiler.js:874:39)
    at ***\node_modules\webpack\lib\Watching.js:173:22
    at ***\node_modules\webpack\lib\Compiler.js:856:14

Localized strings are now being removed from manifest.json

It seems localized strings in the manifest.json file are erroneously being removed during the "compilation" process.

A source manifest.json file containing the following contents:

{
  "manifest_version": 3,
  "name": "__MSG_extensionName__",
  "description": "__MSG_extensionDescription__",
  "version": "1.0"
}

Results in this invalid manifest.json (note the empty name and description properties):

{
  "manifest_version": 3,
  "name": "",
  "description": "",
  "version": "1.0"
}

However, the expected output is:

{
  "manifest_version": 3,
  "name": "__MSG_extensionName__",
  "description": "__MSG_extensionDescription__",
  "version": "1.0"
}

I haven't done any debugging yet, but a cursory glance leads me to believe the transformManifestValuesFromENV() method introduced in v2.0.1 is the culprit, as the was not an issue in v1.0,0 and earlier.

Handle DEP_WEBPACK_COMPILATION_ASSETS

[DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.

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.