I am developing a Chrome Extension with React. In my service worker file, background.js
, I need to import another JS file, which for simplicity, only exports an empty {} for now.
background.js
import store from './testImport';
console.log("Hello Service Worker.")
testImport.js
export default {}
but with no success. I get this error:
I searched for my problem, and most solutions suggested to add "type": "module"
to manifest.json
:
"background": {
"service_worker": "background.js",
"type": "module"
},
I did that and I got a new very vague error message:
An unknown error occurred when fetching the script.
I tried replacing the import with a require:
const store = require('./testImport');
console.log("Hello Service Worker.")
But these results in another error:
Uncaught ReferenceError: require is not defined
Anyway, I don't think require is the solution anyway. Import statements should work, as I've seen them used by others within service worker files and it worked for them. The problem is there are quite a few resources on the internet on this issue and I feel I've exhuasted them all.
Why don't import statements work in my service worker file? Am I doing something wrong?
UPDATE
@wOxxOm's suggestion to add ./ and .js when importing other JS modules works!
However, I need to import NPM packages into the service worker, and I get this error:
Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../"
package.json
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@reduxjs/toolkit": "^1.8.3",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.41",
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"axios": "^0.27.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.0.2",
"react-scripts": "5.0.1",
"react-scroll": "^1.8.7",
"typescript": "^4.7.4",
"watch": "^1.0.2",
"web-vitals": "^2.1.4",
"webext-redux": "^2.1.9"
},
"scripts": {
"start": "react-scripts start",
"build": "INLINE_RUNTIME_CHUNK=false react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"watch": "watch 'npm run build' src"
},
"watch": {
"build": "src/"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/chrome": "0.0.193",
"@types/react-scroll": "^1.8.3",
"autoprefixer": "^10.4.7",
"npm-watch": "^0.11.0",
"postcss": "^8.4.14",
"tailwindcss": "^3.1.3"
}
}