crxjs / chrome-extension-tools

Bundling Chrome Extensions can be pretty complex. It doesn't have to be.
https://crxjs.dev/vite-plugin
2.8k stars 182 forks source link

Extra HTML pages don't find the src file in dev #627

Open corrortiz opened 1 year ago

corrortiz commented 1 year ago

Build tool

Vite

Where do you see the problem?

Describe the bug

When you run the dev server the the extra HTML don't generate the reference to the source file, when you run the build command you get the correct reference:

Output with the vite build command (this works correctly):

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>OffScreen</title>
  <script type="module" crossorigin src="/assets/offscreen.7c2aa4e4.js"></script>
  <link rel="modulepreload" crossorigin href="/assets/chunk-1ebdbb1b.js">
  <link rel="modulepreload" crossorigin href="/assets/chunk-641ab1c8.js">
  <link rel="modulepreload" crossorigin href="/assets/chunk-2a3b33e1.js">
  <link rel="modulepreload" crossorigin href="/assets/chunk-9744cff8.js">
  <link rel="modulepreload" crossorigin href="/assets/chunk-745e3ca4.js">
</head>
<body>
  <div id="root"></div>
</body>
</html>

Output with the vite build command:

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>OffScreen</title>
</head>

<body>
  <div id="root"></div>
  <script src="./index.ts" type="module"></script>
</body>
</html>

I try to add the file with rollup-plugin-copy but its not working as it does not generate the missing file

Reproduction

N/A

Logs

No response

System Info

System:
    OS: macOS 13.1
    CPU: (8) x64 Intel(R) Core(TM) i7-8569U CPU @ 2.80GHz
    Memory: 36.57 MB / 16.00 GB
    Shell: 5.9 - /usr/local/bin/zsh
  Binaries:
    Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v16.16.0/bin/npm
  Browsers:
    Chrome: 109.0.5414.87
    Firefox: 108.0.2
    Safari: 16.2

Severity

blocking an upgrade

rbhalla commented 1 year ago

It would help to understand how you're including this html file in your manifest.json, is it under web_accessible_resources?

If it is, I've found I needed to fully qualify the file location, so instead of ./index.js you may need to do /the/actual/location/index.js relative to where your build is happening.

jacksteamdev commented 1 year ago

@corrortiz Please include at least the manifest and the source HTML file.

Royal-lobster commented 1 year ago

Having the same issue with "@crxjs/vite-plugin": "^2.0.0-beta.15" and "vite": "^4.1.1"

defining the html page on web_accessible_resources

  "web_accessible_resources": [
    {
      "resources": ["src/pages/sidebar/index.html"],
      "matches": ["http://*/*", "https://*/*"]
    }
  ]

in src/pages/sidebar/index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>Sidebar</title>
</head>

<body>
    <div id="__root"></div>
    <script type="module" src="./index.tsx"></script>
</body>

</html>

in src/pages/sidebar/index.tsx

import { createRoot } from "react-dom/client";
import Sidebar from "./components/Sidebar";

function init() {
  const rootContainer = document.querySelector("#__root");
  if (!rootContainer) throw new Error("Can't find Panel root element");
  const root = createRoot(rootContainer);
  root.render(<Sidebar />);
}

init();

It just copies the html as it is, without processing the tsx file linked to it to dist -

CleanShot 2023-04-04 at 23 12 13@2x

Royal-lobster commented 1 year ago

Also, There seems to be an issue with loading the page into an iframe in content. It is functioning correctly on build, however, during development, the page fails to load in the iframe. Interestingly, the page is able to load normally when opened in a new tab.

rbhalla commented 1 year ago

@Royal-lobster, ideally relative imports work, but have you tried referencing the js file relative to the build location (rather than relative to the html file)?

Royal-lobster commented 1 year ago

@Royal-lobster, ideally relative imports work, but have you tried referencing the js file relative to the build location (rather than relative to the html file)?

It's not building the js bundle for that page. unless defining it on roll-up build settings in vite config.

Defining it on the roll-up option input works as expected. (With relative to html file as well)

DaPotatoMan commented 1 year ago

@Royal-lobster Did you find any workarounds for this issue?

Royal-lobster commented 1 year ago

@Royal-lobster Did you find any workarounds for this issue?

For HTML Page, i just added roll up build setting in vite config https://github.com/Royal-lobster/Syncia/blob/main/vite.config.ts

But for iframe not rendering within content script on dev, its painful. i am developing the iframe page isolated in chrome-extension:// link if i were to test on page, i should build every time for every change i make. i think i should make a new issue for it

DaPotatoMan commented 1 year ago

@Royal-lobster in dev you can simply load the http://localhost:5173 url instead of the extension page as a workaround.

DaPotatoMan commented 1 year ago

IFrame loading (extension html page) in content script can be fixed by adding port config in vite.config.ts This issue is most likely connected with #648

Here's the vite config:

server: {
   port: 5173,
   hmr: {
      port: 5173
   } 
}
smeijer commented 1 year ago

I'm having the same issue when creating panes & panels:

manifest:

{
  // …
  devtools_page: 'main.html',
}

main.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <script src="main.js" type="module"></script>
  </body>
</html>

main.js

chrome.devtools.panels.create('my devtool', '', '/panel.html');

chrome.devtools.panels.elements.createSidebarPane('my devtool', (sidebar) =>
  sidebar.setPage('/pane.html'),
);
maitrungduc1410 commented 1 year ago

I'm facing same issue, trying to create a devtools_page, but during yarn dev, the generated devtools.html under dist is just a placeholder, my files are not there (panel.html,...)

Royal-lobster commented 1 year ago

IFrame loading (extension html page) in content script can be fixed by adding port config in vite.config.ts This issue is most likely connected with #648

Here's the vite config:

server: {
   port: 5173,
   hmr: {
      port: 5173
   } 
}

Wow thanks a lot ! You made my life easy

SeekerOfTrueCode commented 1 year ago

I have the same issue with "offscreen.html". I guess it's a duplicate but I link to my repo which is reproducing the issue and also it's in different use case cuz it happens with just .ts file instead of tsx.

Should I close / remove it?

I still can't make workaround work...

supfiger commented 7 months ago

I still can't make workaround work...

@SeekerOfTrueCode have you found a solution?

Currently, I'm trying to figure out how to use Chrome offscreen API with this tool (crxjs/chrome-extension-tools), but I have issues.

What I have:

// vite.config.ts

const PORT = 5173

export default defineConfig({
  // Other stuff
  plugins: [
      react(),
      crx({ manifest }),
  ],
  build: {
    outDir: 'dist',
    rollupOptions: {
      input: {
        offscreen: resolve(process.cwd(), 'src/app/offscreen.html'), // According to https://crxjs.dev/vite-plugin/concepts/pages#extra-html-pages
      },
    },
  },
  server: {
    strictPort: true,
    port: PORT,
    hmr: {
      clientPort: PORT,
    },
  },
}
// manifest.ts

export default defineManifest({
 // Other stuff
  manifest_version: 3,
  permissions: ['offscreen'],
  host_permissions: ['<all_urls>'],
  background: {
    service_worker: 'src/app/background.ts',
    type: 'module',
  },
  web_accessible_resources: [
    {
      resources: ['src/app/offscreen.html'], // According to https://github.com/crxjs/chrome-extension-tools/issues/767#issuecomment-1809560172
      matches: ['<all_urls>'],
    },
  ],
},
// src/app/offscreen.html

<script type="module" src="/src/app/offscreen.ts"></script>
// src/app/background.ts

await chrome.offscreen.createDocument({
  url: chrome.runtime.getURL('src/app/offscreen.html'),
  reasons: ['DOM_PARSER'],
  justification: 'Process Images',
});

...but I'm getting the error Failed to load resource: net::ERR_FILE_NOT_FOUND (since no offscreen js file in dist folder, and also dist/src/app/offscreen.html file even not changed (it still has src="/src/app/offscreen.ts", not .js)

image

GWSzeto commented 6 months ago

@supfiger What worked for me was to bring down the offscreen.html and offscreen.js into the root directory, where the manifest.json is located.

manifest.json

{
  ...
  "permissions": ["activeTab", "offscreen", "tabCapture"],
  "background": {
    "service_worker": "src/background.ts",
    "type": "module"
  },
  "web_accessible_resources": [{
    "resources": ["offscreen.html", "offscreen.js"],
    "matches": ["<all_urls>"]
  }]
}

vite.config.ts

import path from "path"
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { crx } from '@crxjs/vite-plugin'
import manifest from './manifest.json'

export default defineConfig({
  plugins: [
    react(), 
    crx({ manifest }),
  ],
  build: {
    rollupOptions: {
      input: {
        offscreen: 'offscreen.html',
      },
    }
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
})
geanrt commented 1 month ago

To properly use additional HTML pages with scripts in Chrome extensions during development and production with CRXJS, follow these guidelines:

1. manifest.json Configuration

The manifest.json file is essential for defining the configuration of your Chrome extension. You need to specify which resources are accessible and how they should be used.

web_accessible_resources Configuration:

"web_accessible_resources": [
  {
    "matches": ["<all_urls>"],
    "resources": ["src/pages/mypage/index.html"]
  }
]

2. index.html File

The index.html file is the main HTML page for your extension. It should be configured to correctly load your JavaScript or TypeScript.

The only way is to say the total relative path of your app (in this case I put it in default src) and not in (dist)

Example index.html:

<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>mypage</title>
</head>
<body>
  <div id="root-mypage"></div>
  <script type="module" src="/src/pages/mypage/main.tsx"></script>
</body>
</html>

3. vite.config.js Configuration

The vite.config.js file is where you configure how Vite should handle and build your files. To ensure your additional HTML pages are properly included in the build, configure the input for Vite.

vite.config.js Configuration:

import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        kanban: 'src/pages/mypage/index.html',
      }
    },
  },
});

Summary

  1. In manifest.json: Use web_accessible_resources to make your additional HTML pages accessible to the extension.
  2. In index.html: Properly configure the loading of your JavaScript or TypeScript.
  3. In vite.config.js: Ensure your extra pages are included in the build through Rollup configuration.

Following these steps will help you effectively use additional HTML pages with scripts in your Chrome extensions, both during development and in production.

pandasoli commented 4 days ago

The last comment worked for me in parts (thanks geanrt), even though it included the page and the script to the development build it didn't compile the ts file.