How to use NPM modules? - javascript

I'm completely new to frontend web dev with a very basic question. Once I npm install something, how do I actually use it? For example, I just did npm install bootstrap, and I would now like to be able to use the CSS and Javascript that it downloaded. I'm sure I shouldn't have to dig through the directories to find some entry point... so how do I now use bootstrap in my webpage?

Most modules on NPM are used in Node.js, for the server (backend). Node.js has a built-in function require('your-module') to make use of the module. This function is not present on the frontend in the browser. However, there are tools like browserify or webpack and probably others to make the NPM modules and the require function work in the frontend.
If you're just starting out I suggest you take a look at Bower first. With Bower (installed with NPM though) you can pull in all your frontend libraries like jQuery, Bootstrap, etc. to your project folder and you can point your script tags in your HTML to the bower_components/ directory, e.g. <script src="/bower_components/jquery/jquery.min.js"></script>. You can save a list of all libraries used with a version number in a json file called bower.json in the root of your project folder.
Based on this file you can pull in or update all the libraries listed with the use of the command line.

As a really general rule, npm is used for assets your node app will use on the server, while bower (and others) are the equivalent for dependencies that you want to use on the client.
That said, the use is basically the same.
npm (and bower) install the files into your project directory in a standard location. All you really have to do is make sure that location is accessible via a web request (typically, node_modules is not; which is why bower came about), and then embed link and script tags as appropriate in your html:
<script src='/node_modules/bootstrap/js/bootstrap.min.js'></script>

Related

What is the best practice to reference JavaScript libraries that when installed via NPM (in the node_modules folder)?

For example, I created folder, opened it with VS Code. Opened a terminal, used the command npm install jquery, it creates a folder node_modules within my created folder. I then create an HTML file, put HTML template in and now I want to reference jQuery. I know how to reference the files syntactically and all that, I am just looking to understand best practices.
Do I just reference jQuery... JavaScript files within there? Or am I missing a step?
before starting on a new project you should use npm init. this will initialize the project and generate a package.json file. This package.json file is used for managing the project's dependencies(libraries), scripts, version etc.
And after this every time you install a library using npm it will get listed in this package.json file under dependencies section.
example after initializing the npm:
npm i jquery
and you can get it using
const jquery = require('jquery')
or
import jquery from 'jquery';
i.e; without using the relative path, example:
import jquery from '../../node_modules/jquery..'
It sounds like you are missing the build step.
When developing with npm, you usually use a toolchain with compilers, bundlers and minifiers, which read the libraries from the node_modules folder and put the resources in a build folder which actually gets deployed, and from where the js file will be loaded.

Does npm install mean the script only works with Node.js

I'm trying to use an API via it's helpfully developed JS SDK. So the SDK instructions on the GitHub page are to npm install. I'm wondering though, does this imply I have to have Node.js because the SDK has been written specifically for it, or if I just have basic vanilla JS/jQuery, can I just.... Copy the source code from GitHub into my scripts or use it some other way?
It means that the project is using npm to handle dependencies. It has a package.json file that stores what those dependencies are, and npm install will download them into a folder usually called 'node_modules.'
It's dependency management. It doesn't mean it's written for node, but that it uses node to download external dependencies.

How to get Twig.js for the browser

I'm using Twig as my templating system on server side and also want to use it client side (to use the same templates).
I'm also using Bower and tried this command to get Twig.js:
bower install twig.js
But that didn't install all folders as seen here https://github.com/twigjs/twig.js. Then I tried to install other recent branches and commits but still 2 folders were missing at least (bin & src).
After that, I tried cloning the project using Git and it worked because it really got all listed files and folders.
But then when I include twig.js in my HTML file throws this error in the Chrome console log:
twig.js:13 Uncaught ReferenceError: require is not defined
My best guess is that function "require" belongs to Node.js (right?) and there must be some kind of compilation to get Twig.js for the browser (right???).
So, I don't know what is next... How can I get the Twig.js for the browser? (Meanwhile I'm going to get Twig.js from a CDN).
Please help me.
I don't know which version of Twig.js you were using, since the question was posted almost 2 years ago, but probably something 0.9.x or higher. Since that version the maintainers did not commit any JS files compiled for web usage in the root of the project.
So yes, the JS files inside the src/ folder are NodeJS files and you have 'to do something' before you can use them in your browser. The library is using Webpack to build a browser compatible version.
You should run npm install in the root of the GitHub clone to set up the project and then run npm run build in order to build a web version. Check for twig.js in the root after that.
Using a CDN version is also a good option. But because the builds were left out since version 0.9.0 there is no newer version of Twig.js on cdnjs than 0.8.9 while the library is currently on version 1.12.0
Or run npm install twig --save, the compiled files are at:
node_modules/twig/twig.js and
node_modules/twig/twig.min.js
You have to install RequireJS to use require("twig");. Install that first and then run.

Can I exclude files from an NPM package on the installation side?

Is it possible to exclude files from a list of NPM packages in my package.json?
I have a non-browser environment that works a bit differently: every file in node_modules dir becomes part of the production package. So there's no smart treeshaking that imports only the files that I use in my code.
For instance, I use some packages which also carry a lot of tests and i18n files, most of which I don't need and like to remove from my packaged production version. However, they are still included in the end package because the whole package folder is included in the build.
I'm trying to remove as many files from the packages as I can (without doing it manually each time) to save space and compilation time. The environment I use is looping all files in the node_modules directory and adds them to the production package (all packaged using Javascript). I would like a JavaScript solution to remove these files on compilation so the end package is as small as it can be.
I would use bower to manage client-side javascript modules, instead of using npm directly.
Bower packages are simpler than npm equivalents and don't have subfolders with module dependencies. Most will include a "dist" folder with pre-minified javascript. Right out of the box your packages will be smaller than if you use npm.
If you want to go further, you can include some processing in your gulpjs or gruntjs scripts to either manually copy needed files to lib and css folder(s), or use a plugin like gulp-bower-normalize to (somewhat) automatically do the same thing.

Sharing code between AngularJS and Nodejs

What is the best way of sharing code between frontend and backend using javascript, specifically saying between nodejs and angularjs?
Thing is that we are using same enums and constant values such as error codes in both backend and frontend. Right now we just copy&paste each change to both platform which isn't a good solution. There are also some services that could be shared.
I have seen libraries such as browserify; but thats not exactly what I am looking for. I am looking for a solution similar to maven dependency in java. In java, libraries can be shared easily using maven, whereas I can't find a similar way of doing that in javascript.
Is there a way to isolate these services and give them as dependency to nodejs using npm and to angularjs using bower independently? Or what are the ways for sharing the same code between frontend and backend?
There are several ways to do this. The first is that you can make a new package which is required via bower for the front-end code and via npm for the backend code. I have several packages published to both systems.
Install with Bower -- information on how to install modules that aren't in the registry
NPM Install docs -- all the ways to install with npm (private github with auth: git+ssh://git#github.com/[org]/[repo])
Just create a new module with your shared data and install it using both package managers. Both of them allow you to install an unpublished module so if it's private data you can keep it as such.
If your front end requires require.js you can use something like amdefine to make it available to your node backend, or if you're just using legacy window code you can do something like:
var mydata = {};
if(typeof window !== 'undefined'){
window.mydata = mydata;
} else {
module.exports = mydata;
}
If you are sharing a lot of data though I highly recommend looking into browserify to write your entire codebase in commonjs and using browserify to generate your client bundle. There is a laundry list of resources about using browserify, including stuff on how to use browserify and angular together
Disclaimer - I'm still developing this approach and it's a little manual.
I did this using npm, an npm cli called pac, and bower. Pac let's me avoid using npm install in production by keeping the modules as .tgz files (committed to project in source control). With pac, when someone checks out the node project, they run pac install then npm rebuild instead of npm install.
My shared code is kept in a directory (my-module). It has both package.json and a bower.json.
My consuming node app has a package.json dependency for:
"my-module" : "x.y.z"
My consuming client has a bower.json dependency for:
"my-module" : "../relative/path/to/my-module"
When I make updates to my-module, I update my node app by:
Making a tar.gz of the contents of my-module:
tar -czvf my-module.tar.gz -C my-module
Removing the old version from the node app's node_modules
Rerunning npm install path/to/my-module-tar.gz
Rerunning pac (this makes a .tgz of node_modules/my-module)
Committing the updated pac .modules/my-module.tgz
I update my client by:
Removing the old client/bower_components/my-module
Rerunning bower install or bower update

Categories

Resources