1

I'm creating a Chrome extension with React using CRA.

I want to use some helper functions within the /src folder inside of the background.js file, which causes the error Cannot use import statement outside a module because it's in the public folder.

The background.js file has to be in the same folder as the manifest.json file for version 3 of the manifest.json`.

Any suggestions on how to move manifest.json and background.js into the /src folder and still have it build properly with npm run build, which currently uses react-scripts build?

Current Folder Structure: enter image description here

dcotter
  • 312
  • 6
  • 22
  • The background script can be anywhere since Chrome 93 so why don't you restrict your extension from being installed in earlier versions of the browser by specifying minimum_chrome_version? – wOxxOm Mar 01 '22 at 02:17
  • @wOxxOm that sounds like a good suggestion. I'm getting errors when trying to load unpacked - `Could not load background script 'src/background.js'. Could not load manifest.` My manifest.json is loading the script `"service_worker": "src/background.js"` – dcotter Mar 01 '22 at 02:44
  • You need to specify the final path of the file when it's in the `build` directory, not in the source. – wOxxOm Mar 01 '22 at 02:59
  • @wOxxOm When react builds it just builds the public folder and then takes everything else and creates chunk js files. So there isn't a final path to that exact file – dcotter Mar 01 '22 at 03:08
  • Since the error message mentions `src/` it means this string is copied verbatim, consequently it is up to you to specify the correct path there. The correct path won't be in `src`, it will be relative to `build`. If background.js is copied into `build` then there's no additional path. If it's copied into a subfolder there then you need to use that name. If the name gets a hash id then you need to disable this feature. – wOxxOm Mar 01 '22 at 03:15
  • @wOxxOm thanks for the suggestions. Ended up doing a work around of just doing native fetch operations and using chrome storage api inside of `background.js` so I didn't have to import anything. Kept the file inside of the public folder. – dcotter Mar 02 '22 at 03:40

0 Answers0