![見出し画像](https://assets.st-note.com/production/uploads/images/81001223/rectangle_large_type_2_bf61e8ebe35c1c46c6992edc15dda855.jpeg?width=800)
chrome拡張機能で外部ライブラリを使うための方法と失敗した方法
成功
webpackの使用
"production"モードでビルド。jsファイルの冒頭に
import * as THREE from "three";
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
import { gsap } from "gsap";
と入れておけば動く。(書き方は公式ドキュメント参照)
ローカルファイル読み込み
![](https://assets.st-note.com/img/1655620696262-IY1Mgyplmd.png?width=800)
のようにすれば、ダウンロードしたjqueryなどの外部ライブラリも使える。
なお
![](https://assets.st-note.com/img/1655617392217-0RtZehB5gi.png?width=800)
のようにscriptタグ内に処理を書くと
![](https://assets.st-note.com/img/1655617367521-6xwISxvn0m.png?width=800)
となることがある。alert(1);などでも作動しない。jsファイル内に書く。
失敗
CDN(CORSポリシー問題)
manifest.jsonの"host_permissions"
"host_permissions": [
"http://127.0.0.1:8000/*",
"http://13.115.157.139/*",
"https://code.jquery.com/*"
],
結果
![](https://assets.st-note.com/img/1655617245676-GhIYfJzDoz.png?width=800)
また、manifest.jsonに
"content_security_policy": "script-src 'self' https://○○/; object-src 'self'"
を追加しても拡張機能v3では動かないという文章もちらっと見たが、真相は如何に。
webpackの使用(失敗例)
参考サイト(「Three.js webpack」などで検索):
これだけだと「npm run start」で
Module not found: Error: Package path ./build/three is not exported from package
とエラーになってしまうので、index.jsの冒頭に
import * as THREE from "three";
と入れてビルドすればできた。が、それを読み込むと
![](https://assets.st-note.com/img/1655619324330-ntK1a3jHqs.png?width=800)
eval関数は拡張機能では使えない。同ファイルの上の方に「devだからeval使ってるよ」という警告が書かれていたので、webpack.config.jsの「mode」をdevelopmentからproductionにして再度ビルドすると
![](https://assets.st-note.com/img/1655619542892-YUe1mDksdi.png?width=800)
無事、拡張機能でも外部ライブラリを使えるようになりました。
この記事が気に入ったらサポートをしてみませんか?