javascript - 如何在浏览器中使用 npm 模块?甚至可以在本地(PC)中使用它们?

标签 javascript node.js npm module npm-install

我是 npm 模块 和 node.js 的新手,所以这对我来说真的很难。

我有一个包含很多点的 js 代码,对于每个点我都想得到最近的城市。

为此,在其他问题 ( Reverse geocoding with big array is fastest way? - javascript and performance ) 中,一位用户建议我使用两个 npm 模块

const kdbush = require('kdbush');
const geokdbush = require('geokdbush');

// I've stored the data points as objects to make the values unambiguous
const cities = [
  { name: "Abano Terme (PD)", latitude: 45.3594, longitude: 11.7894 },
  { name: "Abbadia Cerreto (LO)", latitude: 45.3122, longitude: 9.5928 },
  { name: "Abbadia Lariana (LC)", latitude: 45.8992, longitude: 9.3336 },
  { name: "Abbadia San Salvatore (SI)", latitude: 42.8800, longitude: 11.6775 },
  { name: "Abbasanta (OR)", latitude: 40.1250, longitude: 8.8200 }
];

// Create the index over city data ONCE
const index = kdbush(cities, ({ longitude }) => longitude, ({ latitude }) => latitude);

// Get the nearest neighbour in a radius of 50km for a point with latitude 43.7051 and longitude 11.4363
const nearest = geokdbush.around(index, 11.4363, 43.7051, 1, 50);

问题是这是我第一次接触这个。此外,我是意大利人,英语说得不太好,在意大利语谷歌中什么也没有。

你能告诉我如何使用这些模块吗?

我必须在我的服务器上安装 Node.js 吗?

是否可以在本地PC上使用模块?

最佳答案

browserify 是正确的方向,但我花了相当多的努力才得出实际的解决方案。我总结了一个short blog为此,这里有一些快速回顾:

比如,您想在 HTML 中使用 emailjs-mime-parserbuffer npm 库。

  1. 安装所需的一切
npm install -g browserify
npm install emailjs-mime-parser
npm install buffer
  1. 编写一个简单的 main.js 作为包装器:
var parse = require('emailjs-mime-parser').default
var Buffer = require('buffer').Buffer
global.window.parseEmail = parse
global.window.Buffer = Buffer
  1. 使用browserify编译一切
browserify main.js -o bundle.js
  1. 现在,您可以在 HTML 文件中使用 bundle.js
<html>
<head>
<script src='bundle.js'></script>
<script>
console.log(window.parseEmail);
console.log(window.Buffer);
</script>
<body>
</body>
</html>

关于javascript - 如何在浏览器中使用 npm 模块?甚至可以在本地(PC)中使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49562978/

相关文章:

node.js - ndb 窗口不显示任何内容

javascript - 随机选择对象

Node.js Mongoose 不以纯文本形式存储连接字符串

node.js - bootstrap 和 npm - 如何在项目中仅导入 "reboot.scss"文件?

node.js - 在 Elasticsearch 的搜索中包含 ObjectId

node.js - 错误: Cannot find module './pulp'

javascript - 在 Amcharts 中动态创建多级钻取

javascript - jQuery 页面根据位置路径名加载

javascript - JWT API token 存储

javascript - 使用 npm 将 fork 存储库安装为依赖项时出错