Using NPM packages without Webpack - node.js

I am used to using NPM packages with Webpack, but I'm wondering how you're supposed to use NPM packages without Webpack.
I know how to install packages. I just don't know how to use them, since you can't just import modules in plain js.

Webpack compiles a bunch of javascript files and combines them into a single one for web distribution. NPM downloads javascript files through packages.
Here's some scenarios where you might use NPM without webpack
You are doing Node.js server-side javascript development. There's no webpack here
You are using a webpack alternative like rollup or browserify
You directly do anything else with the files npm downloads. Maybe you concatenate, throw them in a Makefile or maybe you expose node_modules directly to the world and reference their full paths directly.
Most of my web and server-side development is without webpack.

Why you can't import in plain js?
If you correctly define the package entry point like
"main": "dist/index.js",
"module": "dist/index.js",
Those files can be plain ES6 javascript with named exports or export default, and you can import them after intalling your package with regular import.
You don't need webpack nor babel to make an mpm module. Just put in any folder the files you want to distribute, specifying the main entry point and export elements on that file.
Now... in an angular or react application for example, they may install your component and will use babel and webpack to first transpile your component to ES5 with babel, and then bundle your code together with the rest of their app using webpack.

For front-end, not node.js but still NPM modules.
HTML can import directly ES6 modules but the file must be in .mjs format and provide export default, Module.exports in regular .js file wont't work. This is not a common thing and you'll run into problems if there are subdependencies that don't use ES6 modules. If you find a module that supports it. i.e. some-module
npm install some-module
And in the same directory next to node_modules create index.html pointing straight to the modular bundle
<h1>I'm HTML</h1>
<script type="module">
import SomeModule from './node_modules/some-module/bundle.mjs';
const mod = new SomeModule();
mod.doStuff();
</script>
Here's an article about this https://medium.com/passpill-project/files-with-mjs-extension-for-javascript-modules-ced195d7c84a

npm init
To create a package.json file
npm install --save <package>
To install a package and save it in the package.json file

Related

NPM packages for Next.js - do they need to be in ES5?

I'm bundling a bunch of components I regularly use in apps I create with Next.js into an npm package to make it easier to reuse them between projects, however I'm having difficulty getting it to work.
The big issue I have is that some of my components need to import/require a configuration file from the project root directory (e.g. project/node_modules/mypackage/index.[js/jsx/tsx] needs to import/require project/config.[js/ts]) so I need to ensure the app is able to import components from the npm package, and the npm package is able to import/require from the app.
I use Typescript to compile the npm package (no Webpack or Babel) but I'm not sure what settings to use for target, lib, module and jsx, or if I'm able to just keep it uncompiled as .tsx and .ts files (I'm using the canary branch of Next.js which has built-in Typescript support).
I can't find any information in the documentation, here on SO or via Google search. Any advice?

How to working with css framework in npm

I tryed to use css frameworks lots of times. But i cant found any guide what to do. Just some post from other developers. Can you help me with the guide, how to import and use css framework in my expressjs project.
For instance, i started new project with express generator:
express --view=pug --css=sass
next, i installed materialize
npm install materialize-css
What i must to do next??? How to connect js and sass files with my project? How to compile all, if i tryed to do just a website? Where i can find good guides about such things, if i will have more questions?? Thanks!
npm was originally to get Node Module, but with the essort of the Javascript language (and the advent of browserify, webpack,etc), it has a bit grown up.
In fact, you can even download Bootstrap on npm, that is not a server side framework. Browserify permits you to use AMD/RequireJS/CommonJS on client side so node modules can be used on client side. Same goes for Webpack module bundler.
If you npm install bootstrap (if you don't use grunt or gulp file to move to a dist folder), your bootstrap will be located in some location like below.
"./node_modules/bootstrap/bootstrap.min.css"
You need to include this in your .html file.
For sass if you use grunt then you will be using this plugin grunt-sass to convert sass to css and add the destination file to the .html file. Similarly goes for gulp.

Precompile jsx for React in django-compressor

Using Cygwin on Windows 10 (64 bits)
Installed babel-cli, react and babel-preset-react on top of Node.js, which was installed via Windows Installer (since there is no support for Cygwin.) I installed those Node packages using yarn, in the global modules folder.
In the django-compressor documentation (https://django-compressor.readthedocs.io/en/latest/reactjs/) they say that a precompiler setting does the trick:
COMPRESS_PRECOMPILERS = (
('text/jsx', 'cat {infile} | babel > {outfile}'),
)
However, babel is not recognizing jsx (throwing errors when encountering virtual dom elements.) It's obvious because I am not passing the react preset to the command. But there is no way I can use that preset because I installed in the global module folder and now I am unable to make babel find and use it.
I need one of these possible solutions:
How can I make babel use a preset globally installed (how should I use babel --presets react in a way that works)?
How do I use a .babelrc file in a Django project?
If I were to install the preset locally (which I seem to dislike a lot) how do I make it live with my Django project without making mess out of my project directory structure?
Okay, I banged my head a few times and found a solution:
There is no way to make babel work with presets installed globally. It is mandatory to install them locally. All react, react-dom, babel-core, babel-loader, babel-preset-react (and perhaps babel-preset-es2015 if latest ECMA syntax is desired) must be installed locally.
There is no place to put a .babelrc file where the precompiler would use it. No use to have a babel section in package.json either. Instead, the precompiler setting should pass the presets in command line like:
COMPRESS_PRECOMPILERS = (
('text/jsx', 'cat {infile} | babel --presets react,es2015 > {outfile}'),
)
Just assume that the folder where manage.py lives is also the root for Nodejs packages. Not tested when deployed and running from a wsgi file but maybe the wsgi should also live next to manage.py.
Also, it looks like all these files and folders: node_modules, package.json and yarn.lock (if installing with yarn as I am,) must be included in version control.
EDITED:
I no loger think node_modules should go into version control.

How do I setup Babel 6 with Node JS to use ES6 in my Server Side code?

I have read several times the documentation provided at :
Node API Babel 6 Docs
I'm starting out learning pg-promise following the Learn by Example tutorial and would prefer to work with ES6 and transpile to ES5 with Babel but am unsure of a few things :
After installing babel-core, what preset do I use and where/how do I configure this to work?
The documentation was unclear to me about which file I put: require("babel-core").transform("code", options); into and what parts of that code are place holders. When I use that code, do I just use it one time somewhere and then I can use ES6 in every other file? How would this be achieved?
I read about this .babelrc file and would like to confirm if the actual filename is ".babelrc" or if that is just the file extension and where in relation to the root directory of my project do I put that file.. and how do I link to it?
If I'm using pg-promise should I be using ES6 and Babel or will running : npm install as described under the Testing section for pg-promise be enough and trying to use ES6 with this create more problems?
I was hoping to take advantage of let and const if the need came up during my server side development.
Is there a standard file structure for a node+babel+pg-promise server setup?
Edit
Worth noting that I have also read Node JS with Babel-Node and saw that using this should be avoided. The final answer at the very bottom didn't really make sense to me for similar reasons I'm having trouble following the actual documentation provided by Babel.
1.a What Preset is needed?
You will need to install Babel firstly with npm install babel-core --save-dev in the root directory of your project using a Terminal window like Command Prompt.
Once installed, you will need to install the es2015 preset with npm install babel-preset-es2015 --save-dev. Babel-Core is Promises/A+ Compliant but not ideal for usage due to poor error handling so a library such as Bluebird should be used instead for this purpose. In order to transpile, babel-core will still need to be installed and es2015 enables ES6->ES5 transpiling so you can use fancy things like let and const etc.
1.b Where to put require("babel-core");?
instead, use require("babel-core/register"); and place it inside your Entry file typically called, "server.js". The server.js file will need to use CommonJS (ES5) exclusively.
By using the "require" statement it will apply all relevant transforms to all code being required into the Entry file and all files being required/included into those files.
You point to the Entry file inside package.json under the "main": section.
Package.json is created when you initialise the project with npm init at the root directory of your project inside the Terminal Window
One approach to this would be :
Entry File - server.js
server.js - requires {babel-core and the main ES6 file : config.js/jsx/es6/es}
config.es6 - uses ES6 and has includes(requires) for all other project files that can also use ES6 as they get transpiled by being loaded into the "config" file which is being directly transpiled by babel-core.
2. What is .babelrc?
.babelrc is the filename and should be placed in the same folder as your package.json file (normally the root directory) and will automatically "load" when babel-core is required to determine which preset(s) or plugins are to be used.
Inside .babelrc , you will need to add the following code :
{
"presets": ["es2015"]
}
3. pg-promise Testing Section
A direct quote from the developer recently answered this
You do not need to worry about steps in the Tests, use only the steps in the install. The one in tests relates to the dev dependency installation, in order to run tests. The pg-promise can work with any promise library compliant with Promises/A+ spec.
4. Standard File/Folder Structure for Server Side Projects?
There is no standard way to achieve this task as each project has unique demands. A good starting point would be to place the Entry file in the project root directory, the ES6 Config file in a "scripts" or "src" sub-folder and individual components in folders below that.
e.g.
ROOT/server.js
ROOT/src/config.es6
ROOT/src/component1/files.es6
ROOT/src/component2/files.es6
With this in place, Babel will successfully transpile all ES6 to ES5 and enable support of A+ compliant promises.
To begin using the node.js webserver This Guide provides a bit more insight and in the context of this answer the code shown would be placed into the ES6 config.es6 file and the following code would go into the Entry server.js file :
require("babel-core/register");
require("./src/config.es6");
The process for building Isomorphic web applications is different to this and would likely use things like grunt, gulp, webpack, babel-loader etc another example of which can be Found Here.
This answer is the combination of several key points provided by other answers to this question as well as contributions from experienced developers and my own personal research and testing. Thank you to all who assisted in the production of this answer.
This answer uses this simple directory structure
project/server/src/index.js => your server file
project/server/dist/ => where babel will put your transpiled file
Install babel dependencies
npm install -g babel nodemon
npm install --save-dev babel-core babel-preset-es2015
Add these npm scripts to your package.json file
"scripts": {
"compile": "babel server/src --out-dir server/dist",
"server": "nodemon server/dist/index.js
}
Create a .babelrc file in your project root directory
{
"presets": "es2015"
}
Transpile your directory with
npm run compile
Run your server with
npm run server
I think you should use a tool like grunt or gulp to manage all your "build" tasks. It will automate it for you, and you won't make errors.
In one command, you can transpile your code into babel ES2015 et start your application.
I suggest you to take a look at this simple project. (just install node_modules and launch npm start to start the app.js file)
However, if you really want to use babel manually,
.babelrc is the name of the file, you can see one in this project (redux) to have an example
.babelrc is a config file, if you want to see how it works, you can check this package.json (always redux)
There's actually no standard way that I know. You can use the project skeleton below if needed, and send pull request to improve it :-)
#makeitsimple
Step: 1
npm install nodemon --save
In project directory
Step: 2
yarn add babel-cli
yarn add babel-preset-es2015
Step: 2
In package.json-> scipts change 'start' to the following
start: "nodemon src/server.js --exec babel-node --presets es2015"
Step: 3
yarn start

Front-end dependencies via npm: how does it work?

I've installed backbone via npm, it is placed in node_modules folder (not in web root) how can i include it in my index.html file?
It's possible to write front-end code entirely based on CommonJS (i.e. Node-style) modules.
If you install front-end dependencies through npm you can use a package bundling tool like Browserify to bundle all dependencies into one file. This way you can use the browser-dependent packages in the same way you use server-side packages: with Node's require function. You just require a module (either in node_modules dir or a regular file) and work with it.
Base use of browserify is really simple: Just do browserify clientcode.js > webroot/clientbundle.js, where webroot is your web root. Then include clientbundle.js in your html file.
clientcode.js should be the client's "main" script, comparable to the "app.js" (or similar) of an Express app or so. It can be as big as you want, but you could just as well use it only as bootstrap code to run functions defined in other CommonJS modules.
Note that you can easily mix browserified dependencies with regular dependencies. Any scripts that you include beforehand (say a non-browserified jquery) will just become a global, and browserify does not prevent you from accessing globals.
Beware though: Some packages distributed via npm based on client-side libraries do not conform (entirely) to CommonJS spec. Some may not export anything, some may (unexpectedly) create globals, etc.
See also Backbone app with CommonJS and Browserify .
Some alternatives to browserify:
https://github.com/michaelficarra/commonjs-everywhere
https://github.com/medikoo/modules-webmake
https://github.com/webpack/webpack
I haven't tried them though.
While the idea of using npm for both backend and frontend may sound tempting–it certainly did to me–try Bower or Ender.js instead for frontend dependencies. I personally prefer bower, because I can more easily include it into my requireJS module structure. It will keep you from foaming at the mouth with frustration.
Front-end dependency I would recommend using Bower. There are many components available for you to use and they are really easy to setup.

Resources