Подтвердить что ты не робот

Webpack - require ('node_modules/leaflet/leaflet.css)

Итак, я пытаюсь создать приложение карты с помощью webpack и leaflet. Я могу потребовать leaflet.js из моего файла map.js, но я не могу вызвать файл leaflet.css, не получив ошибку.

Мой текущий webpack.config.js выглядит следующим образом:

'use strict'

var webpack = require('webpack'),
    path = require('path'),
    HtmlWebpackPlugin = require('html-webpack-plugin'),
    srcPath = path.join(__dirname, 'src');

module.exports = {
    target: "web",
    cache: true,
    entry: {
        app: path.join(srcPath, "index.js")
    },
    resolve: {
        alais: {
            leaflet_css: __dirname + "/node_modules/leaflet/dist/leaflet.css"
        }
    },
    module: {
        loaders: [
          {test: /\.js?$/, exclude: /node_modules/, loader: "babel-loader"},
          {test: /\.scss?$/, exclude: /node_modules/, loader: "style!css!sass!"},
          {test: /\.css?$/, loader: "style!css!"}
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin("common", "common.js"),
        new HtmlWebpackPlugin({
          inject: true,
          template: "src/index.html"
        }),
        new webpack.NoErrorsPlugin()
      ],
    output: {
        path: path.join(__dirname, "dist"),
        publicPath: "/dist/",
        filename: "[name].js",
        pathInfo: true
    }
}

И мой файл main.js выглядит так:

var $ = require('jquery'),
    leaflet = require('leaflet');

require("./sass/main.scss");
require("leaflet_css");

var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="#" onclick="location.href='http://osm.org/copyright'; return false;">OpenStreetMap</a> contributors'
}).addTo(map);

L.marker([51.5, -0.09]).addTo(map)
    .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
    .openPopup();

console.log('I got called');

Каков правильный подход связывания файлов css от сторонних поставщиков через webpack?

Я видел, что этот проект был leaflet хранится в каталоге libs... в чем причина этого, зачем хранить его в libs, если он установлен в директорию node_modules через npm?

Это очень учебное упражнение, поэтому любые указатели очень ценятся!:)

4b9b3361

Ответ 1

Итак, получается, что ответ представляет собой комбинацию webpack resolve.alias и загрузчика файлов. Мой новый файл webpack выглядит следующим образом:

'use strict'

var webpack = require('webpack'),
    path = require('path'),
    HtmlWebpackPlugin = require('html-webpack-plugin'),
    srcPath = path.join(__dirname, 'src');

module.exports = {
    target: "web",
    cache: true,
    entry: {
        app: path.join(srcPath, "index.js")
    },
    resolve: {
        extensions: ['', '.html', '.js', '.json', '.scss', '.css'],
        alias: {
            leaflet_css: __dirname + "/node_modules/leaflet/dist/leaflet.css",
            leaflet_marker: __dirname + "/node_modules/leaflet/dist/images/marker-icon.png",
            leaflet_marker_2x: __dirname + "/node_modules/leaflet/dist/images/marker-icon-2x.png",
            leaflet_marker_shadow: __dirname + "/node_modules/leaflet/dist/images/marker-shadow.png"
        }
    },
    module: {
        loaders: [
          {test: /\.js?$/, exclude: /node_modules/, loader: "babel-loader"},
          {test: /\.scss?$/, exclude: /node_modules/, loader: "style-loader!css-loader!sass-loader!"},
          {test: /\.css?$/, loader: "style-loader!css-loader!"},
          {test: /\.(png|jpg)$/, loader: "file-loader?name=images/[name].[ext]"}
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin("common", "common.js"),
        new HtmlWebpackPlugin({
          inject: true,
          template: "src/index.html"
        }),
        new webpack.NoErrorsPlugin()
      ],
    output: {
        path: path.join(__dirname, "dist"),
        publicPath: "/dist/",
        filename: "[name].js",
        pathInfo: true
    }
}

И тогда все, что мне нужно сделать, это использовать значки в файле .js

require("./sass/main");
require("leaflet_css");
require("leaflet_marker");
require("leaflet_marker_2x");
require("leaflet_marker_shadow");

Прекрасный!!!:)

Ответ 2

Мне удалось сделать это проще. Просто нужно добавить загрузчиков для css и для png

loaders: [
    { test: /\.css$/, loader: 'style-loader!css-loader' },
    {
        test: /\.png$/,
        loader: 'url-loader',
        query: { mimetype: 'image/png' }
    }
]