Home  >  Q&A  >  body text

Chrome Extension: Import ES6 modules in content scripts

<p>In <strong>Chrome 61</strong>, support for JavaScript modules was added. Now I'm running Chrome 63. </p> <p>I'm trying to use a module in a Chrome extension content script using the <code>import</code>/<code>export</code> syntax. </p> <p>In<strong><code>manifest.json</code></strong>:</p> <pre class="brush:php;toolbar:false;">"content_scripts": [ { "js": [ "content.js" ], } ]</pre> <p>In<strong><code>my-script.js</code></strong> (with <strong><code>content.js</code></strong> same directory):</p> <pre class="brush:php;toolbar:false;">'use strict'; const injectFunction = () => window.alert('hello world'); export default injectFunction;</pre> <p>In<strong><code>content.js</code></strong>:</p> <pre class="brush:php;toolbar:false;">'use strict'; import injectFunction from './my-script.js'; injectFunction();</pre> <p>I get this error:<strong><code>Uncaught syntax error: Unexpected identifier</code></strong></p> <p>If I change the import syntax to <code>import {injectFunction} from './my-script.js';</code> I get this error: <strong><code>Uncaught SyntaxError: Unexpected token {</code></strong>< /p> </p><p>Is there a problem using this syntax in <strong><code>content.js</code></strong> in the Chrome extension (because in HTML you have to use < ;code> <script type="module" src="script.js "></code> syntax), or am I doing something wrong? It seems strange that Google is ignoring support for extensions. </p></script> </code></p>
P粉141035089P粉141035089442 days ago578

reply all(2)I'll reply

  • P粉739079318

    P粉7390793182023-08-28 14:20:34

    Use dynamic import()< /code> function.

    Unlike the unsafe workaround using