Javascript: NPM, Webpack and Babel
NODE.JS and NPM
Node.js
is a javascript runtime build. Its package ecosystem npm
is the largest ecosystem of open source libraries in the world. So first install Node.js
and NPM
.
Then in your project folder run npm init
. Answer couple of questions, it will create package.json
file in your project folder.
Now we install webpack
, webpack-cli
and live-server
. --save-dev
means that it will be installed as development dependency. It will be listed under devDependencies
in your package.json
file (because it is used during development). As an example jquery
would be installed only using --save
as it is used during project is live.
Webpack
is most commonly used asset bundler. It bundles all our javascript files into one file.
Here is how our project structure will look.
Create webpack.config.js
in your project folder.
We create index.js
and test.js
files to test if webpack will bundle then into one file.
index.js
test.js
We can run webpack from cli with npm run dev
(or npm run build
which will be smaller as it is minimized), which will bundle our js files to one bundle.js
file. dev
is defined in package.json
file.
Webpack Dev Server and Babel
With this previous setup, we must run npm run dev
each time we make some change. To automatize this, we will use dev server, so changes will be reloaded automatically after each change. We will use webpack-dev-server
for this. For copying index.html
from src
to dist
folder automatically, we will use html-webpack-plugin
. To transform code from ES6
or newer to ES5
we will use Babel
. Some code cant be transformed (for example promises, because they just dont exist in older versions of javascripts), for that will be used babel-polyfill
, which will just add that code and not transform it.
This is how will look updated scripts
part of package.json
file. We added start
script. We will then run npm run start
, it will then run in the background and refresh each time we change files.
This is how will look updated webpack.config.js
also with babel
installed. Babel
is used to transform ES6
and later javascript code back to ES5
code, for compatibility with older browsers.
We must also create .babelrc
file in app folder.
When i tested this, it runs to error Cannot find module '@babel/core'
. I fixed this with following command.