XXX is not defined - Importing Class from OpenLayers Node Module in Django

Having difficulty getting the Node OpenLayers to work within Django. npm and ol are installed and the files are in a node_modules folder in my project. I included the node_modules folder in my STATICFILES_DIRS in settings.py.

I'm including the OpenLayers modules within my template, map.html:

<script type="module" src="{% static 'ol/dist/ol.js' %}"></script>
<script type="module" src="{% static 'ol/Map.js' %}"></script>
<script type="module" src="{% static 'ol/View.js' %}"></script>
<script type="module" src="{% static 'ol/layer/Tile.js' %}"></script>
<script type="module" src="{% static 'ol/source/OSM.js' %}"></script>
<script type="text/javascript">
    import "{% static 'ol/layer/Tile.js' %}";
    const map = new ol.Map({
        target: 'my-map',
        layers: [
            new ol.Layer.Tile({
                source: ol.Source.OSM()
            })
        ],
        view: new ol.View({
            center: [40, -70],
            zoom: 2
        })
    });
</script>

Which appears to be working as I can see the files load within my browser's dev tools.

But when I try to use the classes within the modules I get the error:

Uncaught ReferenceError: ol is not defined


OTHER METHODS I'VE TRIED:

I've also tried calling the class names directly:

<script type="text/javascript">
    const map = new Map({
        target: 'my-map',
        layers: [
            new Tile({
                source: OSM()
            })
        ],
        view: new View({
            center: [40, -70],
            zoom: 2
        })
    });
</script>

But get the same error:

Uncaught ReferenceError: Tile is not defined

The OpenLayers docs show using the import statement:

import "{% static 'ol/layer/Tile.js' %}";

but when I try that I get the error:

Uncaught SyntaxError: Cannot use an import statement outside a module

I've also found recommendations to try:

const Tile = require("{% static 'ol/layer/Tile.js' %}");

but get the error:

Uncaught ReferenceError: Require is not defined
Back to Top