Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

import - How to configure webpack.config.js in Vaadin application? importing CSS / PNG from node_modules (Leaflet library)

I'm trying to integrate Leaflet.js into my Vaadin application. For some reason I couldn't load the CSS and the markers... After a lot of reading I figured out(I hope I did) that I need to configure webpack.config.js in order to be able to load everything properly. I tried every solution but none of them seems to work

here is my leaflet-connector.js:

import L from 'leaflet';  
import style from 'leaflet/dist/leaflet.css';
import 'leaflet/dist/leaflet.css';
import markericon2x from 'leaflet/dist/images/marker-icon-2x.png';
import markershadow from 'leaflet/dist/images/marker-shadow.png';
import markericon from 'leaflet/dist/images/marker-icon.png';

window.Vaadin.Flow.Legacy = window.Vaadin.Flow.Legacy || {};

window.Vaadin.Flow.LeafletJs = {
    init: function(configurationJson,element) {
        if (element.$connector) {
            return;
        }
        loadCSS(style);
        element.$connector = {
            init: function(configurationJson,element) {
                if(navigator.geolocation)
                    navigator.geolocation.getCurrentPosition(function(position){
                        const {latitude} = position.coords;
                        const {longitude} = position.coords;
                        const coords = [latitude, longitude];
                        
                        
                        const map = L.map(element).setView(coords, 13);
                        


                            console.log(markericon);
                            console.log("----------------------------------------------------------");
                           L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                           attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                           }).addTo(map);
                           
                           
                            L.marker(coords).addTo(map)
                            .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
                            .openPopup();    
                    
                            delete L.Icon.Default.prototype._getIconUrl;

                            
                            L.Icon.Default.mergeOptions({
                                iconRetinaUrl: markericon2x,
                                iconUrl: markericon,
                                shadowUrl: markershadow
                              });
                    
                            
                    },
                function() {
                    alert('could not get your location');
                })
                
            },
          

        },
      
        function loadCSS(css) {
            var exists = document.getElementById("____fx-leaflet_____") !== null;
            if (exists) return;
            var head = document.getElementsByTagName('head')[0];
            var style = document.createElement('style');
            style.id = "____fx-leaflet_____";
            style.innerHTML = css;
            head.insertBefore(style, head.firstChild);
        },
        
        element.$connector.init(configurationJson,element);
    }
    }

You see, i did this ugly thing with the loadCSS function just to be able to import the CSS.

here is the LeafletJs.java:

import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.function.SerializableConsumer;


@NpmPackage(value = "leaflet",version = "1.7.1")
@NpmPackage(value = "file-loader",version = "1.1.4")
@JsModule(value = "./js/leaflet-connector.js")


public class LeafletJs extends Div {

        private boolean initialized = false;   

    public LeafletJs() {
        addClassName("leafletjs"); 
    }

    @Override
    protected void onAttach(AttachEvent attachEvent) {       
        super.onAttach(attachEvent); //To change body of generated methods, choose Tools | Templates.
        initConnector();
    }

    private void initConnector() {
        if (initialized == false) {   
            initialized = true;    
            runBeforeClientResponse(ui -> ui.getPage().executeJavaScript(
                    "window.Vaadin.Flow.LeafletJs.init($0, $1)", null, 
                    getElement()));            
        }
    }
   
    void runBeforeClientResponse(SerializableConsumer<UI> command) {
        getElement().getNode().runWhenAttached(ui -> ui
                .beforeClientResponse(this, context -> command.accept(ui)));
    }
      
}

So, my question is: how can I configure the webpack?

webpack.config.js:

const merge = require('webpack-merge');
const flowDefaults = require('./webpack.generated.js');

module.exports = merge(flowDefaults, {
    
 });

I tried this:

const merge = require('webpack-merge');
const flowDefaults = require('./webpack.generated.js');



module.exports = merge(flowDefaults, {
   module: {
    rules: [
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
   });

and tried a lot of similar configuration, but somehow I couldnt figure out why these solutions are not working for me. I think I'm missing something, but I have no clue what

question from:https://stackoverflow.com/questions/65903489/how-to-configure-webpack-config-js-in-vaadin-application-importing-css-png-fr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

so I really struggled to find any good solutions, but realized that this webpack config helps to import the leaflet markers:

module.exports = merge(flowDefaults, {
 
        module: {
            rules: [
                        {   test: /.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/i, 
                            loader: "file-loader?name=build/images/[name].[ext]"
                        }
            ]
        }

   }); 

leaflet-connector.js:

import markericon2x from 'leaflet/dist/images/marker-icon-2x.png';
import markershadow from 'leaflet/dist/images/marker-shadow.png';
import img from 'leaflet/dist/images/marker-icon.png';

       ...

delete L.Icon.Default.prototype._getIconUrl;
                            L.Icon.Default.mergeOptions({
                                iconRetinaUrl: markericon2x,
                                iconUrl: img,
                                shadowUrl: markershadow
                              });

                        L.marker(coords).addTo(map)
                            .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
                            .openPopup();    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...