How to use import Leaflet in Sails.js?

Viewed 428

Super basic question: I want to install and use the Leaflet module in my Sails.js project. First thing, I install it in using npm i leaflet --save. This successfully updates the dependencies list in the package.json file.

To use it, I write the following code inside a page script:

mounted: async function() {
  //…
  console.log('hello world!!!!');
  var leaflet = require("leaflet");
},

Sails.js complains: Uncaught (in promise) ReferenceError: require is not defined.

Why? If I need to create a hook first, what would it need to contain?

2 Answers

Modules installed through the package manager npm are to be used in the server-side of things (controllers, actions, etc.), not in the browser.

You could use solutions such as Browserify or Webpack, but in this case it's just better to download Leaflet from the website and add the folder under assets/dependencies.

Finally, you can import the JavaScript Leaflet files in layout.ejs (inside the views/layouts folder):

<% /* Auto-injected «script» tags: */ %>
<!--SCRIPTS-->
// ...
<script src="/dependencies/leaflet/leaflet.css"></script>

And for CSS:

<% /* Auto-injected «link» tags: */ %>
<!--STYLES-->
// ...
<link rel="stylesheet" href="/dependencies/leaflet/leaflet.css">

I would guess this is the best approach as the Sails.js starter template is importing Boostrap 4 in the same way.

You don't have to require anything, once you npm installed it just add the leaflet.js, leaflet.markercluster.js and leaflet.css in your header and you're done.

You can use the short example of init map from their site and it'll work.

Related