crxjs / chrome-extension-tools

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

Following Get Started for React guidance for content scripts results in nonworking build #454

Open myktra opened 2 years ago

myktra commented 2 years ago

Build tool

Vite

Where do you see the problem?

Describe the bug

Followed the "90 Second" tutorial for React on crxjs.dev, got the basic popup working. Continued on to the step where a content script is added. Vite throws an error to the terminal when adding src/content.jsx as recommended and running npm run dev.

It appears that any reference to React causes the exception to be thrown. Modifying src/content.jsx to do this works; notice the commented lines:

import React from 'react'
import ReactDOM from 'react-dom/client'
// import App from './App'
import './index.css'

const root = document.createElement('div')
root.id = 'crx-root'
document.body.append(root)

// ReactDOM.render(
//   <React.StrictMode>
//     <App />
//   </React.StrictMode>,
//   root,
// )

alert('this runs, so long as React is not invoked')

When creating a production build via npm run build you'll see an error thrown in the browser console:

TypeError: o.render is not a function
    at content.jsx.8bfc7cc5.js:1:142

Reproduction

Following the guidance for the Vite plugin provided on crxjs.dev. So minimally this is a documentation issue. Here's a repo showing the current state of the project. Uncomment the lines in src/content.jsx to reproduce the error.

https://github.com/myktra/crxjs-vite-plugin-content-script-issue

Logs

> vite-project@0.0.0 dev
> vite
  VITE v3.0.3  ready in 721 ms
  ➜  Local:   http://127.0.0.1:5173/
  ➜  Network: use --host to expose
8:36:58 AM [vite] ✨ optimized dependencies changed. reloading
8:36:58 AM [crx] files ready in 928ms
8:36:58 AM [crx] files start dist
8:36:59 AM [crx] files ready in 423ms
8:45:26 AM [vite] page reload src/content.jsx
8:45:26 AM [crx] files start dist
8:45:26 AM [crx] error from file writer:
Error: Could not load /id-__x00__react-jsx-dev-runtime-NY5FA.js (imported by ../../../../../../src-App.jsx-fecjs.js): Unable to load "__x00__react/jsx-dev-runtime" from server.
    at Object.load (file:///Users/xxx/Documents/spm/src/vite-project/node_modules/@crxjs/vite-plugin/dist/index.mjs:248:17)
    at async file:///Users/xxx/Documents/spm/src/vite-project/node_modules/rollup/dist/es/shared/rollup.js:22096:98
    at async Queue.work (file:///Users/xxx/Documents/spm/src/vite-project/node_modules/rollup/dist/es/shared/rollup.js:22773:32)

System Info

System:
    OS: macOS 11.6.7
    CPU: (8) x64 Intel(R) Core(TM) i7-8569U CPU @ 2.80GHz
    Memory: 103.05 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.16.0 - ~/Library/Caches/fnm_multishells/22810_1659009572252/bin/node
    Yarn: 1.22.17 - ~/.yarn/bin/yarn
    npm: 8.11.0 - ~/Library/Caches/fnm_multishells/22810_1659009572252/bin/npm
    Watchman: 2022.07.04.00 - /usr/local/bin/watchman
  Browsers:
    Brave Browser: 103.1.41.100
    Chrome: 103.0.5060.134
    Edge: 103.0.1264.51
    Safari: 15.5
  npmPackages:
    @crxjs/vite-plugin: ^1.0.13 => 1.0.13 
    vite: ^3.0.0 => 3.0.3

Severity

blocking all usage of RPCE

myktra commented 2 years ago

I was able to work around this issue by specifying use of the classic runtime option for @vitejs/plugin-react, making a change to vite.config.js, though presumably it would be ideal to not to have to use the classic runtime?

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

// https://vitejs.dev/config/
export default defineConfig({
  // need to use the classic runtime
  plugins: [react({ jsxRuntime: 'classic' }), crx({ manifest })]
})
jacksteamdev commented 2 years ago

@myktra Thanks for taking the time to make this repro. This is a Vite 3 issue. Downgrading to Vite@2.9.15 and '@vitejs/plugin-react'@1.3.2 works as expected. I'll need to update the docs and articles.

I'm in the middle of upgrading the content script file writer and Vite 3 support will come with that in #427.

AntonOfTheWoods commented 2 years ago

@jacksteamdev , is there any rough idea of when Vite 3 support might drop? I see there are still updates to https://github.com/crxjs/chrome-extension-tools/pull/427 but it isn't clear whether it might still take a while, or whether anyone might be able to help.

jacksteamdev commented 2 years ago

Vite 3 support is available for testing in the current beta release: @crxjs/vite-plugin@2.0.0-beta.1

AntonOfTheWoods commented 2 years ago

@jacksteamdev , I tried to take it (beta.2) for a test drive but immediately got errors like the following:

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/anton/dev/ntc/transcrobes/frontend/node_modules/get-port/index.js from /home/anton/dev/ntc/transcrobes/frontend/node_modules/@crxjs/vite-plugin/dist/index.cjs not supported.                                     
Instead change the require of index.js in /home/anton/dev/ntc/transcrobes/frontend/node_modules/@crxjs/vite-plugin/dist/index.cjs to a dynamic import() which is available in all CommonJS modules.

Which makes me think that I probably have to make some changes to my code (or maybe just config) in order to be able to use it. At the moment I am forcing 1.0.13 and it appears to be creating something that I can use with vite 3 (everything that I have tested works, though there might be stuff I'm missing...).

Is there a migration guide, or should it just work OOTB?

JoeyDoey commented 2 years ago

Vite 3 support is available for testing in the current beta release: @crxjs/vite-plugin@2.0.0-beta.1

Assuming a default setup now with:

is it still necessary to have the preamble in the config? i.e. :

    crx({
      manifest,
      // πŸ‘‡ is this still necessary ?
      contentScripts: {
        preambleCode: false,
      },
    }),

Yields the following error in content script (if preambleCode: false) but maybe config steps might have changed.

error in content script:

image

I'm not sure the error resolution suggested explains the steps. Let me know if I should move this convo elsewhere πŸ‘

Error: @vitejs/plugin-react can't detect preamble. Something is wrong. See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201

jacksteamdev commented 2 years ago

@JoeyDoey With the beta version of CRXJS, React works out of the box.

I've verified that the Vite config below works with npm init vite@latest and npm i @crxjs/vite-plugin@beta @types/chrome -D.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { crx, defineManifest } from "@crxjs/vite-plugin";

const manifest = defineManifest({
  manifest_version: 3,
  name: 'some name',
  version: '1.0.0',
  content_scripts: [{
    js: ['./src/main.tsx'],
    matches: ['<all_urls>']
  }]
})

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [crx({ manifest }), react()]
})

OFC, you'll need to follow the getting started guide to update src/main.tsx to work with a content script.

jacksteamdev commented 2 years ago

Which makes me think that I probably have to make some changes to my code (or maybe just config)

@AntonOfTheWoods You are right! This error was caused by certain project configs. I've fixed this error in the latest beta release: npm i @crxjs/vite-plugin@beta -D.

JoeyDoey commented 2 years ago

@JoeyDoey With the beta version of CRXJS, React works out of the box.

I've verified that the Vite config below works with npm init vite@latest and npm i @crxjs/vite-plugin@beta @types/chrome -D.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { crx, defineManifest } from "@crxjs/vite-plugin";

const manifest = defineManifest({
  manifest_version: 3,
  name: 'some name',
  version: '1.0.0',
  content_scripts: [{
    js: ['./src/main.tsx'],
    matches: ['<all_urls>']
  }]
})

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [crx({ manifest }), react()]
})

OFC, you'll need to follow the getting started guide to update src/main.tsx to work with a content script.

Awesome. Thanks @jacksteamdev I'll give that a shot. Great work on this tool!

AntonOfTheWoods commented 2 years ago

@jacksteamdev , not sure what is going on now but I spent quite a while trying to work it out to no avail...

> cross-env DEBUG=vite-plugin-pwa:* BASE_URL=/ SOURCE_MAP=true SW=true NODE_OPTIONS='--max-old-space-size=8192' vite --force --config vite.ext.config.ts --mode=development

✘ [ERROR] [plugin externalize-deps] Failed to resolve entry for package "@crxjs/vite-plugin". The package may have incorrect main/module/exports specified in its package.json.

    node_modules/esbuild/lib/main.js:1327:27:
      1327 β”‚         let result = await callback({
           β•΅                            ^

    at packageEntryFailure (file:///home/anton/dev/ntc/transcrobes/frontend/node_modules/vite/dist/node/chunks/dep-c842e491.js:35293:11)
    at resolvePackageEntry (file:///home/anton/dev/ntc/transcrobes/frontend/node_modules/vite/dist/node/chunks/dep-c842e491.js:35290:5)
    at tryNodeResolve (file:///home/anton/dev/ntc/transcrobes/frontend/node_modules/vite/dist/node/chunks/dep-c842e491.js:35031:20)
    at file:///home/anton/dev/ntc/transcrobes/frontend/node_modules/vite/dist/node/chunks/dep-c842e491.js:63965:40
    at requestCallbacks.on-resolve (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:1327:28)
    at handleRequest (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:697:19)
    at handleIncomingPacket (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:719:7)
    at Socket.readFromStdout (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:647:7)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:315:12)

  This error came from the "onResolve" callback registered here:

    node_modules/esbuild/lib/main.js:1251:20:
      1251 β”‚       let promise = setup({
           β•΅                     ^

    at setup (file:///home/anton/dev/ntc/transcrobes/frontend/node_modules/vite/dist/node/chunks/dep-c842e491.js:63955:27)
    at handlePlugins (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:1251:21)
    at buildOrServeImpl (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:942:5)
    at Object.buildOrServe (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:750:5)
    at /home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:2085:17
    at new Promise (<anonymous>)
    at Object.build (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:2084:14)
    at build (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:1931:51)
    at bundleConfigFile (file:///home/anton/dev/ntc/transcrobes/frontend/node_modules/vite/dist/node/chunks/dep-c842e491.js:63918:26)

  The plugin "externalize-deps" was triggered by this import

    vite.ext.config.ts:1:326:
      1 β”‚ ...njected_original_import_meta_url = "file:///home/anton/dev/ntc/transcrobes/frontend/vite.ext.config.ts";import { crx } from "@crxjs/vite-plugin";
        β•΅                                                                                                                                ~~~~~~~~~~~~~~~~~~~~

failed to load config from /home/anton/dev/ntc/transcrobes/frontend/vite.ext.config.ts
error when starting dev server:
Error: Build failed with 1 error:
node_modules/esbuild/lib/main.js:1327:27: ERROR: [plugin: externalize-deps] Failed to resolve entry for package "@crxjs/vite-plugin". The package may have incorrect main/module/exports specified in its package.json.
    at failureErrorWithLog (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:1566:15)
    at /home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:1024:28
    at runOnEndCallbacks (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:1438:61)
    at buildResponseToResult (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:1022:7)
    at /home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:1134:14
    at responseCallbacks.<computed> (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:671:9)
    at handleIncomingPacket (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:726:9)
    at Socket.readFromStdout (/home/anton/dev/ntc/transcrobes/frontend/node_modules/esbuild/lib/main.js:647:7)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:315:12)
A-Shleifman commented 2 years ago

@AntonOfTheWoods https://github.com/crxjs/chrome-extension-tools/issues/567#issuecomment-1304843039

myktra commented 1 year ago

The initial workaround (use Vite 2; no support for Vite 3 at the time) and now the latest plugin beta and Vite 3 have cleared up the original issue for me, as others have also observed here. I think this one can be closed!

AntonOfTheWoods commented 1 year ago

Hmmm. This is a bit of a difference in philosophy. I am a firm adherent of keeping tickets open until stable releases containing the fixes are released. Put a note "waiting for a release" but keep open. But this ain't my repo, so I humbly submit to whatever is decided! Thanks for the fix anyway!

myktra commented 1 year ago

Seems reasonable; I think there are some other issues that have been closed under similar circumstances (including a related one I just closed but maybe shouldn't have). Maybe we just call 2.0.0-beta9 stable enough? πŸ˜ƒ

AntonOfTheWoods commented 1 year ago

Sounds good to me, I haven't noticed any quacks personally!

karlhorky commented 1 year ago

@myktra @jacksteamdev so what do you think about closing this issue?

Or, is there a timeline for a non-beta version?