5

I've used JetBrains WebStorm to create a Node.js Express App. I used npm (via File->Settings->Node.js and NPM) to install a package called validator which is used for string validation.

The package was installed under node_modules, which is fine. If I do var validator = require('validator'); in my server code, I can use the validation functions successfully.

The problem is that I would also like to use validator in client JavaScript. I can include the script like this:

<script src="/javascripts/xss-filters.min.js"></script>

But that means I have to copy xss-filters.min.js from the node_modules folder into the public javascripts folder. Then, if I ever update the package with npm, the files will be out of sync.

Is there some way to reference node_modules from my view, or to create some sort of linked file or file reference or something? I'd rather not have to maintain this manually.

Andy West
  • 12,302
  • 4
  • 34
  • 52

2 Answers2

7

you should consider using browserify, which allows you to require modules in the browser by building all the dependencies. so basically you code like you would do in server side http://browserify.org

Edgar Zakaryan
  • 576
  • 5
  • 11
  • 1
    I appreciate this is a very old question / answer - but I'm trying to get my head around this. Without browserify, all node_modules need to be referenced in script tags in the HTML? Surely when NPM updates a package, the script path is then broken? – DJC Feb 13 '17 at 17:09
  • i installed browserify but for me require() is still not working! do i have to add something in my code to use browserify? – Zeeshan Ahmad Khalil Oct 28 '19 at 08:06
1

You can done it by using another node.js module, called node-browserify

You can try to use bower, or yeoman. bower - will simplify the process to include js libs. yeoman - will help you to build projects with the the libraries that you need.

Community
  • 1
  • 1
mabc224
  • 722
  • 2
  • 10
  • 18