Closed4

Chrome拡張機能開発でmoduleを使う方法

fuutotfuutot

シンプルなJavaScript環境でChrome拡張機能を開発していると以下のようなエラーが発生した

Uncaught SyntaxError: Cannot use import statement outside a module (at content.js:1:1)

どうやら、コンテンツスクリプトでmoduleは使えないらしい

fuutotfuutot

ビルドツールの一つにviteがあるみたい
以下のような設定ファイルを書いて、npx vite buildでビルドできた

import {defineConfig} from 'vite';

export default defineConfig({
  build: {
    outDir: 'dist', // 出力ディレクトリ
    rollupOptions: {
      input: './src/content.js', // エントリーポイント
      output: {
        entryFileNames: 'content.js', // 出力ファイル名
      },
    },
  },
});
fuutotfuutot

ビルドしたファイルをコンテンツスクリプトに指定するとmoduleが使用できた

{
    "content_scripts": [
        {
            "matches": ["https://zenn.dev/*/scraps/*"],
            "js": ["dist/content.js"]
        }
    ]
}
このスクラップは2日前にクローズされました