Webpack 要求不起作用

Webpack require won't work

本文关键字:不起作用 Webpack      更新时间:2023-09-26

所以我有这段代码,使用jQuery...

require("./locations.js");
$( document ).ready(function() {
    console.log("Adding locations..");
        $.each(locations, function(key,loc) {
          if (loc.popular == 1) $(".popular-list").append("<a href='#'><li class='loc'>Hello</li></a>");
        });
        $.ajax({
            url : "changelog.txt",
            dataType: "text",
            success : function (data) {
                $(".the-log").html(data);
            }
        });
    });

locations.js包含以下内容:

var locations = [
{ name: "Varrocka", lng: 22.5, lat: -15.52249812756166, popular: 1 },
{ name: 'Lumbridge', lng: -43.644025847699496, lat: 25.9661865234375, popular: 1 },
{ name: "Monastery", lng: -4.0924072265625, lat: -5.714379819235291 },
{ name: "Edgeville", lng: 2.4884033203125, lat: -6.0094592380595495, popular: 1 },
{ name: "Varrock Palace", lng: 22.412109375, lat: -6.882800241767556 },
{ name: "Digsite", lng: 46.043701171875, lat: -17.266727823520508 }
];

但是,在上面第一个代码块的$.each行上,会发生此错误:

Uncaught ReferenceError: locations is not defined

现在,我以为我只是发起了它...这是我的webpack.config.js

module.exports = {
    entry: "./src/js/main.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    }
};

并且bundle.jslocations.js与它们存储在js/bundle.js上并重复js/locations.js位于同一目录中。

我做错了什么?

你需要从locations.js导出一些东西,比如

module.exports = [
    { name: "Varrocka", lng: 22.5, lat: -15.52249812756166, popular: 1 },
    ...
];

然后将其用作

var locations = require("./locations.js");;