To clarify first, I'm not making a case that NPM should totally replace Grunt, Gulp or Webpack. Although there are interesting articles related to that topic which I put in the reference section at the end of this article. I'm presenting this as an additional option that you can consider in your project. The advantage of using NPM script based on my experience are:
The first thing to do is to create a project folder named "npm-es6-tutorial". It will contain a simple website project that serves static files.
Next is to initalize our "package.json" file and install a module for serving HTTP. We will be selecting the module "http-serve" which is a simple webserver that can be used for development. Our webserver is not important within the context of the topic build tools. This should work in any webserver or frameworks like Apache, Nginx, Laravel or ExpressJS.
We now have a running website that can be accessed at http://localhost:4000. Let's now build a very simpl home page. Create "index.html" and copy or type the code below.
Let's download and use jquery to be able to also show how to use libraries from "node_modules" to the browsers.
The three libraries installed are:
To now use Babel in the command line. Run the following:
Now we can run babel using NPM scripts capability. First delete the compiled file to see that it will be generated again.
You will see that "main.bundle.js" was generated again similar to the direct usage of babel command that we've used earlier. As you observed, we can use "npm run" command on whatever is in the "scripts" of "package.json" using the key assigned to the command. In this case, we assigned it as "babel" but we can choose any name.
Refresh "index.html" in your browser. You will see that we are getting error "require is not defined" even though we already transformed our codebase to es5 which is the current universally supported in browsers. The reason for this is even though our codebase is now in es5 version, it is not yet built to work in browser environment. That is because babel es5 transformation does not assume that the environment will be browser as long as it satisfies es5 specs. For making this work in browser, we'll have to use another tool, "browserify":
Edit package.json again and add the following after the "babel" line we've included earlier.
A better solution is to use "Babelify" which is a Browserify transform package for Babel. This will allow to directly transform the es2015 codebase in browser usable form without the need for two-step process we presented.
In package.json, replace the browserify command with the code below:
Below is the full package.json. You may also check the github codebase here.