[英]Import es6 module in chrome extension mv 3 background script with typescript
我是构建Chrome 扩展 mv3的新手。 现在我正在使用Typescript作为我的主要语言创建一个扩展。 我尝试导入Es6 模块,但是当我加载扩展时,Chrome 显示“未捕获的 ReferenceError:未定义导出”。
这是我的项目结构
| .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
我的 manifest.json 文件:
{
"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"
]
}
]
}
我的 tsconfig.json 文件:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"typeRoots": [
"./node_modules/@types"
],
"sourceMap": true,
"outDir": "./public/js",
"sourceRoot": "./src",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
在我的 background.utils.ts 文件中:
const myFunction = ()=>{}
export default myFunction
在我的 background.ts 文件中:
import myFunction from './background.utils/'
但是 Chromes 说即使我在 Internet 上尝试了几种方法,例如在 mainifest.json 文件中添加“type”:“module”或在 tsconfig.json 文件中添加远程“module”:“commonjs”,也没有定义导出。
你们知道为什么会这样吗?
期待收到大家的回答
太感谢了。
您已经尝试插入清单,“类型:模块”?
"background": {
"service_worker": "./public/js/background.js",
"type": "module"
},
有一个很棒的插件叫做crxjs ,你只需要在vite.config.ts
中更新它并给你的 manifest.json 提供路径(它只适用于 mv3)
1.将crxjs添加到你的项目中
npm install @crxjs/vite-plugin -D
2.创建或更新manifest.json
{
"manifest_version": 3,
"name": "CRXJS React Vite Example",
"version": "1.0.0",
"action": { "default_popup": "index.html" }
}
3.使用清单路径更新您的 vite.config.ts 文件
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 }),
],
})
运行你的项目之后,现在 config.js 将被捆绑,你可以在其中导入包
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.