Import es6 module in chrome extension mv 3 background script with typescript

Viewed 1880

I'm new at building a Chrome extension mv3. Now I'm creating an extension using Typescript as my main language. I've tried to import Es6 modules, but when I loaded the extension, Chrome says that "Uncaught ReferenceError: exports is not defined".

Here's my project structure

|   .babelrc
|   manifest.json
|   package.json
|   tsconfig.json
|   webpack.config.js
|
+---public
|   +---html
|   |       index.html
|   |       popup.html
|   |
|   +---js
|   |       background.d.ts
|   |       background.js
|   |       background.js.map
|   |       background.utils.d.ts
|   |       background.utils.js
|   |       background.utils.js.map
|   |       index.html
|   |       main.js
|   |       popup.d.ts
|   |       popup.js
|   |       popup.js.map
|   |
|   \---styles
|           popup.css
|
\---src
    |   background.ts
    |   background.utils.ts
    |   popup.ts
    |
    \---@types
        \---background
                index.d.ts

My manifest.json file:

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "./public/js/background.js",
    "persitent": true
  },
  "action": {
    "default_popup": "./public/html/popup.html"
  },
  "minimum_chrome_version": "92",
  "permissions": [
    "management",
    "scripting",
    "activeTab",
    "webRequest",
    "tabs",
    "webNavigation",
    "storage"
  ],
  "content_scripts": [
    {
      "matches": [
        "*://*.nytimes.com/*"
      ],
      "js": [
        "./public/js/popup.js"
      ]
    }
  ]
}

My tsconfig.json file:

{
  "compilerOptions": {
    "target": "es2016",                                  
    "module": "commonjs",                                
    "typeRoots": [
      "./node_modules/@types"
    ],                                 
    "sourceMap": true,                            
    "outDir": "./public/js",                      
    "sourceRoot": "./src",                        
    "esModuleInterop": true,                      
    "forceConsistentCasingInFileNames": true,     
    "strict": true,                               
    "skipLibCheck": true                          
  }
}

In my background.utils.ts file:

const myFunction = ()=>{}
export default myFunction

In my background.ts file:

import myFunction from './background.utils/'

But Chromes says that export is not defined even though I've tried serveral methods on Internet like add "type": "module" into the mainifest.json file or remote "module":"commonjs" in tsconfig.json file.

Do you guys have any idea why this happens?

Looking forward to receiving you guys' answers

Thank you so much.

1 Answers

You already tried to insert into manifest, "type: module"?

"background": {
  "service_worker": "./public/js/background.js",
  "type": "module"
},
Related