I'm facing challenges while trying to incorporate OpenLayers (v5.3.0) into a Laravel 5.7 project, particularly with importing ol from node_modules.
Following the instructions on https://www.npmjs.com/package/ol, I installed ol using the command:
npm install ol
Next, I made modifications to my resources\js\app.js file, which now looks like this:
require('./bootstrap');
require('ol');
UPDATE: I also attempted the following in resources\js\app.js, but without success:
require('./bootstrap');
const ol = require('ol');
The webpack.mix.js file includes the following configuration:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js/app.js')
.sass('resources/sass/app.scss', 'public/css');
In addition, I have included relevant lines of code in map.blade.php for displaying the OpenLayers map as intended:
<script src="{!! mix('js/app.js') !!}"></script>
...
<div id='map' style='z-index: 1; width: 100%; height:calc(100% - 56px);'>
<script>
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
new Map({
target: 'map',
layers: [
new TileLayer({
source: new XYZ({
url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
})
})
],
view: new View({
center: [0, 0],
zoom: 2
})
});
</script>
</div>
I have executed the npm run dev
command.
However, when testing in Chrome, an error "Uncaught SyntaxError: Unexpected identifier" is triggered, pointing to the line in map.blade.php:
import Map from 'ol/Map';
UPDATE: I also tried installing all dependencies by running the command:
npm install --save-dev parcel-bundler
No errors were encountered during the installation process, but the same Chrome error persists.
UPDATE: To address the issue, I attempted moving the JavaScript code out of map.blade.php into a new file (mapscript.js), and then importing it in map.blade.php as follows:
<script src="{!! asset('js/mapscript.js') !!}" type="module"></script>
Nevertheless, a new error emerged:
Uncaught TypeError: Failed to resolve module specifier "ol/Map". Relative references must start with either "/", "./", or "../".
Following that, I experimented with transferring certain lines of code from app.js to mapscript.js, both with the require('ol');
and const ol = require('ol');
statements, but the error continues to persist.
Despite exploring numerous potential solutions on platforms such as Stack Overflow, and considering alternatives like utilizing ol outside of npm, I am still unable to resolve this issue. While I acknowledge that incorporating OpenLayers through npm and Mix is the preferred method, I am currently stuck trying to identify the cause of this problem. Any assistance provided would be greatly appreciated.