Over the past few years, web development has evolved from applications containing a small amount of JavaScript code to applications that have a dependency tree between complex JavaScript code and code. Webpack can analyze the structure of the project, find Javsscript modules and other assets, and then collect packages for use by the browser. Take a look at a simple webpack use example.
1. Tool Installation and Environment configuration
The first thing to install NPM is to install node. JS directly. Then use NPM install-g webpack Global installation, or install locally in the corresponding project directory. Next we create a project catalog, such as Sample1. Then create two directory apps and public. Create two files under the app directory Greeter.js and Main.js,public directory to place a index.html file. Then execute the NPM init command to create the Package.json file. If you do not have a global installation of Webpack, you also use the NPM install Webpack command, which will have a more Node_modules directory under the directory.
2. Code implementation
The greeter.js and Main.js codes are implemented as follows:
// Main.js var greeter = require ('./greeter.js ');d Ocument.getelementbyid (' root '). AppendChild (Greeter () ); // Greeter.js function () { var greet = document.createelement (' div '); = "Hi there and greetings!" ; return greet;};
The index.html is implemented as follows:
<!DOCTYPE HTML><HTMLLang= "en"> <Head> <MetaCharSet= "Utf-8"> <title>Webpack Sample Project</title> <Head> <Body> <DivID= "root"></Div> <Scriptsrc= "Bundle.js"></Script> <Body><HTML>
Notice that we used the Bundle.js file, and we'll use Webpack to generate the file in the third step.
3. Packing with Webpack
Next we use the Webpack app/main.js public/bundle.js to generate the Bundle.js file. All we have to do is tell Webpack that the master file is Main.js,webpack and will find all the dependent files that are used and package all the files together.
Then open the index.html file with your browser and you'll see the hi there and greetings! statement.
Webpack using tutorial one