Webpack - first project

To prepare us properly for setting up an Angular project, let's first go through a simple project that showcases all the common scenarios that we will be using to set up Angular.

First off, we need to install webpack. This is accomplished by running the following command:

npm install webpack -g

After successful installation, it's time to try it out. First off, let's create a few files with the following content:

//index.html
<html></html>

//app.js
var math = require('./mathAdd');
console.log('expect 1 and 2 to equal 3, actual =', math(1,2));

//mathAdd.js
module.exports = function(first, second){
return first + second;
}

Run the following command:

webpack ./app.js bundle.js

This will crawl all dependencies starting with app.js and create a bundle.js file from them. To use said bundle.js, add a script tag to index.html so it now looks as follows:

<html>
<script src="bundle.js"></script>
</html>

To see your app in a browser, you need a web server that can host your files. There are many small, lightweight web servers; Python comes with one, for example. I am going to recommend one called http-server. It can easily be installed by typing the following in the Terminal:

npm install http-server -g

After it is installed, place yourself in the same directory as the index.html file and invoke the web server by typing the following:

http-server -p 5000

Navigate to http://localhost:5000 in your browser and open up devtools; the following should be displayed:

expect 1 and 2 to equal 3, actual = 3

Congratulations, you have successfully created your first webpack bundle and you have a working app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset