Tooling

The objectives of the setup are:

  • Import Web scripts (.webjs) as strings without the need of an additional bundle;
  • Statically check Web scripts for syntax errors;
  • Statically check Web scripts compatibility given targeted WebViews versions;
  • Test the Web scripts behaviors.

Babel

To import .webjs files as strings, we will use babel-plugin-inline-import with webjs or whichever extension you are using for your WebView scripts. This plugin will allow you to import scripts as strings instead of transpiling the module.

Install Plugin

yarn add --dev babel-plugin-inline-import

Configure Plugin

babel.config.js
{
// ...
"plugins": [
[
"babel-plugin-inline-import",
{
"extensions": ["webjs"]
}
],
// ...
]
}

Configure Metro

We need to tell metro to resolve webjs files:

metro.config.js
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts }
} = await getDefaultConfig();
return {
resolver: {
sourceExts: [...sourceExts, "webjs"]
}
};
})();
important

You might have issue with caching:

  • With metro, you will need to change the file importing the webjs extension in order to invalidate the cache;
  • With jest, you will need to clear cache after changing a webjs file. Use jest --clearCache.
tip

To circumvent this issue

ESLint

You can use @formidable-webview/eslint-config-webjs to target .webjs files with specific config:

  • Enforce ECMAScript 5 to make sure it runs on reasonably old WebView backends.
  • Enforce a list of supported web engines with the outstanding eslint-plugin-compat. We make sure we don't use recent Web APIs without a fallback or polyfill.

Install Plugin

yarn add --dev estlint-plugin-compat \
@formidable-webview/eslint-config-webjs

Configure Plugin

eslint.js
module.exports = {
root: true,
overrides: [
{
files: ["*.webjs"],
extends: "@formidable-webview/eslint-config-webjs",
},
],
};

Typescript

Add a declaration file to resolve .webjs extensions as strings:

webjs.d.ts
declare module '*.webjs' {
const source: string;
export default source;
}

Jest

See this guide.

Syntax Highlight

The last thing you need to do is associate JavaScript syntax with webjs or whichever extension you have chosen in your text editor.

VSCode

Add this file association in your settings.json:

settings.json
{
"files.associations": {
"*.webjs": "javascript"
}
}

Github

Add this line to your .gitattributes file:

.gitattributes
*.webjs linguist-language=Javascript

Gitlab

Add this line to your .gitattributes file:

.gitattributes
*.webjs gitlab-language=Javascript

Debugging WebViews

See this guide.

Last updated on by Jules Sam. Randolph