簡體   English   中英

通過 Mix 將 node_modules 導入 Laravel

[英]Importing node_modules into Laravel via Mix

我正在嘗試在 Laravel 5.7 項目中使用 OpenLayers (v5.3.0),但是在從 node_modules 導入 o​​l 時遇到了很多麻煩。

我安裝 ol 如下(基於https://www.npmjs.com/package/ol ):

npm install ol

然后我更新了我的 resources\\js\\app.js,它現在只包含以下內容:

require('./bootstrap');
require('ol');

編輯:我還在 resources\\js\\app.js 中嘗試了以下內容,但沒有成功:

require('./bootstrap');
const ol = require('ol');

我的 webpack.mix.js 包含以下內容:

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js/app.js', )
   .sass('resources/sass/app.scss', 'public/css');

我在名為 map.blade.php 的文件中還有以下相關行,我想在該文件中顯示 OpenLayers 地圖:

<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>

我也運行了npm run dev

在 Chrome 中測試時,我收到“Uncaught SyntaxError: Unexpected identifier”,指的是 map.blade.php 中的以下行:

import Map from 'ol/Map';

編輯:我還運行了以下命令以確保安裝了所有依賴項:

npm install --save-dev parcel-bundler

運行上述程序時我沒有收到任何錯誤,但 Chrome 中仍然存在相同的錯誤。

編輯:我還嘗試將 javascript 從我的 map.blade.php 轉移到一個新文件 (mapscript.js) 中,然后將其導入 map.blade.php(在“地圖”div 之后),如下所示:

<script src="{!! asset('js/mapscript.js') !!}" type="module"></script>

但是后來我得到了以下錯誤:

Uncaught TypeError: Failed to resolve module specifier "ol/Map". Relative references must start with either "/", "./", or "../".

之后,我嘗試將以下行從 app.js 移到 mapscript.js:

require('ol');

並且還嘗試了相同的方法:

const ol = require('ol');

但是在這兩種情況下,相同的 Uncaught TypeError 仍然存在。

我已經在 Stack Overflow 和其他地方嘗試了許多類似問題的解決方案,我也嘗試在 npm 之外使用 ol,但我沒有找到任何可以解決我問題的方法。 我相信使用 npm 和 Mix 是將 OpenLayers 構建到我的項目中的最佳方式,但我不知道為什么它不起作用。 真的很感激一些幫助。

經過反復試驗,我讓 OpenLayers 6.1 與 Laravel 6.2 一起使用 Mix、Webpack 和 ES6 模塊導入。 訣竅是將所有 javascript 編寫在一個單獨的文件中,並將其打包到 app.js 中。

使用 npm 將 openlayers 安裝到 Laravel 項目中:

npm install ol

在您的 Laravel 項目中的resources/js/myMap.js (與bootstrap.jsapp.js一起)創建一個新文件,並將您的 OpenLayers javascript 代碼放入其中。

讓我們使用從https://openlayers.org/en/latest/doc/tutorials/bundle.html 上的官方文檔復制的簡短代碼示例

import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

const map = new Map({
    target: 'osm_map',
    layers: [
        new TileLayer({
            source: new OSM()
        })
    ],
    view: new View({
        center: [0, 0],
        zoom: 0
    })
});

我們需要將其導出為文字對象以使其可用於其他代碼,因此插入如下所示的五行。

import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

var my_map = {                       // <-- add this line to declare the object
    display: function () {           // <-- add this line to declare a method 

        const map = new Map({
            target: 'osm_map',
            layers: [
                new TileLayer({
                    source: new OSM()
                })
            ],
            view: new View({
                center: [0, 0],
                zoom: 0
            })
        });

    }                                // <-- close the method
};                                   // <-- close the object
export default my_map;               // <-- and export the object

將這兩行添加到bootstrap.js的末尾,以便它包含我們的代碼,並將我們的對象 my_map 附加到全局窗口對象,以便我們可以從頁面中引用它。

import my_map from './myMap.js';
window.my_map = my_map;

現在通過執行npm run dev它們全部捆綁起來。 請注意,我們使用的是 Laravel 的默認 webpack 和 mix 配置 - 我們根本不需要編輯webpack.mix.js npm run devmyMap.js文件中的代碼復制到app.js 每次編輯myMap.js時,我們都需要運行它。 npm run watch可用於自動執行此步驟)。

要在刀片模板中顯示地圖,我們需要有一個與 OpenLayers 地圖目標匹配的 div id, osm_map上面示例代碼中的osm_map 這是一個最小的刀片。

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <style>
        #osm_map {
            position: absolute;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>

<div id="app">
    <div id="osm_map"></div>
</div>

<script src="{{ asset('js/app.js') }}" ></script>

<script type="text/javascript">
    window.my_map.display();
</script>

</body>
</html>

筆記:

  1. div id="osm_map" 匹配 openlayers 目標。
  2. OpenLayers CSS 也被捆綁並在此處引用。 這會設置 OpenLayers 控件的樣式。
  3. 當我們調用 my_map.display() 方法時顯示地圖。

這成功地在 Laravel 刀片模板中顯示了一個交互式 OpenLayers 地圖。

安裝ol包:

npm install ol

在 js 文件夾(bootstrap.js 和 app.js 存在的地方)的資源目錄中創建一個文件名 map.js

resources/js/map.js

在 map.js 中編寫您的 Openlayer 代碼(示例代碼):

import 'ol/ol.css';
import {Map,View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

const map = new Map({
target: 'map',
layers: [
    new TileLayer({
        source: new OSM()
    })
],
view: new View({
    center: [0, 0],
    zoom: 0
             })
});

現在,轉到webpack.mix.js ,它通常在最后。

在文件末尾添加.js('resources/js/map.js', 'public/js')

webpack.mix.js將如下所示:

const mix = require('laravel-mix');
/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.js('resources/js/map.js', 'public/js');

現在,在終端中npm run dev

你的*.blade.php代碼應該是下面的示例代碼:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>Using Webpack with OpenLayers</title>
    <style>
        #map {
            height: 100%;
            width: 100%;
            left: 0;
            top: 0;
            overflow: hidden;
            position: fixed;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script type="text/javascript" src="{{ asset('/js/map.js') }}"></script>
</body>
</html>

不允許直接從公共文件夾導入節點模塊。 在這里,我們在項目中導入模塊,並在公共文件夾中的webpack的幫助下使用它。

對於生產: npm run production在終端

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM