While testing out Electron I wanted to begin building something with Bootstrap (my favorite “get-it-done” CSS framework). Since Electron requires build steps I’m going to use Laravel-Mix to handle getting Bootstrap 4, jQuery and Electron to work together.
The biggest challenge was running down a Bootstrap error when trying to compile jquery.min.js, bootstrap.min.js and tether.min.js into a single vendors.js file:
Uncaught Error: Bootstrap’s JavaScript requires jQuery. jQuery must be included before Bootstrap’s JavaScript.
Turns out, jQuery, when compiled is a module and not attached to the browser “window.” This means that jQuery or $ calls don’t resolve because window.jQuery or window.$ do not exist.
I got it all sorted out by pulling jQuery out of vendors.js and adding a require in the head on page. The resulting head of my Electron’s index.html looks like so (I have my html in a single folder in my electron project):
You may see an error here but don’t worry. In Electron (at least in their starter samples) the final script tag is below the closing body tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Electron Thingie</title>
<link rel="stylesheet" href="../dist/app.css">
<script>
window.$ = window.jQuery = require('../node_modules/jquery/dist/jquery.min.js')
</script>
<script src="../dist/vendors.js"></script>
<script src="../dist/app.js"></script>
</head>
<body>
<!-- BUILD A THING -->
</body>
<script>
// You can also require other files to run in this process
require('../renderer.js')
</script>
</html>
You may see an error here but don’t worry. In Electron (at least in their starter samples) the final script tag is below the closing body tag.
If you’re interested, my package.json looks like so:
Dropped in Bootstrap, jQuery, Laravel-Mix and Electron. Also add a few scripts to speed up development.
{
"name": "electron-starter",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron .",
"webpack": "cross-env NODE_ENV=development webpack --progress --hide-modules",
"dev": "cross-env NODE_ENV=development webpack --watch --progress --hide-modules",
"hmr": "cross-env NODE_ENV=development webpack-dev-server --inline --hot",
"production": "cross-env NODE_ENV=production webpack --progress --hide-modules",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"bootstrap": "^4.0.0-alpha.6",
"jquery": "^3.1.1",
"laravel-mix": "^0.3.0",
"electron": "^1.4.1"
}
}
And my build steps are insanely simple thanks to Laravel-Mix:
let mix = require('laravel-mix').mix;
mix.combine([
'node_modules/tether/dist/js/tether.js',
'node_modules/bootstrap/dist/js/bootstrap.js'
], 'dist/vendors.js');
mix.js('src/app.js', 'dist/');
mix.sass('src/app.scss', 'dist/');
You’ll want to follow Laravel-Mix’s installation docs to get mix in place once you install the dependency.