Search code examples
javascripthtmlthymeleafopenlayerses6-modules

Uncaught SyntaxError: Cannot use import statement outside a module with OpenLayers


I am new using OpenLayers (an open-source JavaScript library for displaying map data in web browsers as slippy maps). I am using it with Thymeleaf (a Java XML/XHTML/HTML5 template engine that can work both in web and non-web environments).

I have this piece of code:

<div class="windowContentMap">
    <div id="map" class="map"></div>
        <script>
          /*<![CDATA[*/
          import '/pradera/css/ol.css';
          import Map from '/css/Map';
          import View from '/css/View';
          import TileLayer from '/css/layer/Tile';
          import OSM from '/css/source/OSM';

          var map = new Map({
            layers: [
              new TileLayer({
                source: new OSM()
              })
            ],
            target: 'map',
            view: new View({
              projection: 'EPSG:4326',
              center: [0, 0],
              zoom: 2
            })
          });
          /*]]>*/
        </script>
    </div>
</div>

but on the line import '/pradera/css/ol.css';

I have this error:

Uncaught SyntaxError: Cannot use import statement outside a module

Solution

  • That's because, as the error states, you cannot use the import statement outside an ES6 module.

    To solve it, make your script to a module by adding type="module" to your script tag, like:

    <div class="windowContentMap">
        <div id="map" class="map"></div>
            <script type="module">
              /*<![CDATA[*/
              import '/pradera/css/ol.css';
              import Map from '/css/Map';
              import View from '/css/View';
              import TileLayer from '/css/layer/Tile';
              import OSM from '/css/source/OSM';
    
              var map = new Map({
                layers: [
                  new TileLayer({
                    source: new OSM()
                  })
                ],
                target: 'map',
                view: new View({
                  projection: 'EPSG:4326',
                  center: [0, 0],
                  zoom: 2
                })
              });
              /*]]>*/
            </script>
        </div>
    </div>
    

    Read more about ES6 modules