Using ES6 modules in Chrome extensions
Hello all,
Starting from Chrome 61+, modules syntax has been steady implemented in Chrome. Today (Chrome 65), I felt like refractoring one of my extensions to benefit of it.
First, how can you split the code into separate modules? You can check out this commit of mine, long story short, imagine you have similar code in your options and popup files.
options.html
<script src="options.js"></script>
options.js
const MY_VALUE = true;
const getMyValue = () => { return MY_VALUE; };
alert(`options reads: ${getMyValue()}`);
popup.html
<script src="popup.js"></script>
popup.js
const MY_VALUE = true;
const getMyValue = () => { return MY_VALUE; };
alert(`popup reads: ${getMyValue()}`);
We probably would like avoid duplicating the code as much as possible. Using ES6 modules we can obtain the same result with the following code:
myComponent.js
const MY_VALUE = true;
export const getMyValue = () => { return MY_VALUE; };
options.html
<script src="options.js" type="module"></script>
options.js
import { getMyValue } from './myComponent.js';
alert(`options reads: ${getMyValue()}`);
popup.html
<script src="popup.js" type="module"></script>
popup.js
import { getMyValue } from './myComponent.js';
alert(`popup reads: ${getMyValue()}`);
This seems much better to me and, after running some benchmark tests on the Chrome Task Manager, I didn’t notice any exceeding memory consumption by using modules syntax.
VERY IMPORTANT:
1. You have to add type=”module” to your scripts tags. Example:
<script src="options.js" type="module"><script>
2. You have to specify the full path of the javascript file in your import statement. Example:
import { getMyValue } from './myComponent.js';
3. All module code is run in strict mode.
Enjoy your shiny new Javascript syntax!
No comments yet.