What is the correct way to use an npm-installed package?

Asked

Viewed 619 times

2

To explain my question I will use jquery as an example. I installed jquery from npm (npm install jquery). Then npm created the jquery dist node_modules folder where the jquery file I need is (jquery.js).

To use this file should I point to this node folder? In other words, if my project folder is at the same level as the node_modules folder I should do this to use my js?:

<script src="../node_modules/jquery/dist/jquery.js">

I created a . js file both in my project folder and in the same level folder of the node_modules folder and tried to import it like this:

var $ = require('jquery')

but it doesn’t work. What would be the right way to do it?

  • Sergio, I even looked for something related to my question but I didn’t find it. Anyway thank you, this other question answered my.,

2 answers

2


I particularly like to use NPM only for server dependencies and the Bower for customer dependencies.

To install Bower just use the command:

npm i bower -g

After doing this you can create a file called .bowerrcas described here with the location for you to install client dependencies.

The usage mode is similar to NPM and you can save the dependencies with --save and things like that.

EDIT 1

Taking into account the article npm and front-end Packaging you can create another package.json inside your briefcase publicto their dependencies of front-end, but this is not recommended.

  • Thanks for the tip, but I only want to use npm

  • @Felipecoelho added one more piece of information that might suit you.

0

The way you loaded jQuery in the first example was to work, except for the fact that you didn’t close the tag <script>, maybe that’s the problem?

Functional example:

<!DOCTYPE html>
<html lang="pt-br">
<head>
  <meta charset="UTF-8">
  <title>Testando jQuery</title>
</head>
<body>

  <script src="./node_modules/jquery/dist/jquery.js"></script>

  <script>
    $(window).ready(function () {
      alert("Testando jQuery");
    });
  </script>

</body>
</html>
  • If he’s inside the briefcase public maid in the express, for example, it will not work no.

  • My doubt is not whether it works or not, but whether this is the right way to use a package from npm

Browser other questions tagged

You are not signed in. Login or sign up in order to post.