Skip to content

Instantly share code, notes, and snippets.

@nathanchicken
Last active November 27, 2019 09:38
Show Gist options
  • Save nathanchicken/c25432d7f98e4112b1d1c8b74eb23b07 to your computer and use it in GitHub Desktop.
Save nathanchicken/c25432d7f98e4112b1d1c8b74eb23b07 to your computer and use it in GitHub Desktop.
jQuery in webpack build for West Division / Mica
// this doesn't have to be in app.js,
// just somewhere to spin up...
const getBookings = () => import("@/parts/bookingDates")
import { docReady } from "@/libs/helpers";
docReady( () => {
// decide on what will define the presence of the jquery app,
// i.e. the presence of a particular element. If this element
// exists, we will spin up the files:
const jqElement = document.getElementById('jquery-element');
// element does exist so...
if ( jqElement ) {
// trigger the function, that resolves a promise,
getJqueryTest().then( m => {
// 'm' is the module,
// so if export default function....
// then 'default' is the function to execute,
// this will activate the module
m.default()
})
}
})
import $ from 'jQuery'
export default function () {
$(function () {
var $container = $('#jquery-element');
$container.html('<div class="p-8 bg-black text-white">jQuery Works!</div>');
// booking dates file from Mica goes here, plain jQuery works
// ...
}
{#
In a twig file, ensure to include the jQuery file. Webpack isn't going
to wait for this, nor load this. So, we have to be sure that we don't
load it async (this is fine for a booking page). It will be ready
and in the global scope by the time webpack inits.
#}
{% extends "_layouts/default.twig" %}
{% block scripts %}
<script
src="https://code.jquery.com/jquery-3.1.0.js"
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
crossorigin="anonymous">
</script>
{% endblock %}
{% block content %}
<div class="p-8">
{# add an element to 'detect' above for the booking app. #}
<div id="jquery-element">
Loading
</div>
</div>
{% endblock %}
// in the file, after the main 'return'
// add this, it doesn't really matter where
...
externals: {
jQuery: 'jQuery'
},
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment