Webpack project example

Advertising

Last Updated : |  

Webpack is not the only bundle tool on the web but a very useful and one of the most used. Here we put together a small package together with Plugin etc. for our project with Webpack. When creating you will understand step by step how it is structured and can then expand it more easily. In this tutorial we will create a development environment for a single page.

To get started, we first create a project in an editor of our choice or use Microsoft's Visual Studio Code Editor. If you have not already installed Node.js then do so now that we need it.

If you have Node.js installed then we can start installing Webpack.
Open your terminal (console) and switch to the project path.

USERNAME$ cd /Users/USERNAME/Project/Webpack

Configuration of the package.json

Create the package.json by typing the following in the console.

Webpack$ USERNAME$ npm init -y

This creates the following file package.json with the following content. So a clean standard package.json which is not yet configured, but you can also create and configure it manually, you do not have to use the console.


// JSON CODE
     0  {  1      "name": "Webpack",  2      "version": "1.0.0",  3      "description": ",  4      "main": "index.js",  5      "dependencies": {},  6      "devDependencies": {},  7      "scripts": {  8          "test": "echo \"Error: no test specified\" && exit 1",  9      },  10      "keywords": [],  11      "author": ",  12      "license": "ISC"  13  } 

    Now enter the following line for the console and confirm with Enter to start the local installation of Webpack.

    Webpack$ USERNAME$ npm install webpack webpack-cli --save-dev

    After the installation we can see in the package.json the webpack and webpack-cli have been added.

    But we could also manually enter these two lines in the package.json and run npm install and it would have the same effect.


    // JSON CODE
       0  {  1      "name": "Webpack",  2      "version": "1.0.0",  3      "description": ",  4      "main": "index.js",  5      "dependencies": {},  6      "devDependencies": {  7          "webpack": "^4.28.4",  8          "webpack-cli": "^3.2.1",  9      },  10      "scripts": {  11          "test": "echo \"Error: no test specified\" && exit 1",  12      },  13      "keywords": [],  14      "author": ",  15      "license": "ISC"  16  } 

      So now that you know that you can write all the dev dependencies and install all the ones you need, that could look like below. If you run with this package.json then npm install all Dev dependencies are installed inside.


      // JSON CODE
         0  {  1      "name": "Webpack",  2      "version": "1.0.0",  3      "description": ",  4      "private": true,  5      "main": "index.js",  6      "dependencies": {},  7      "devDependencies": {  8          "clean-webpack-plugin": "^1.0.0",  9          "html-webpack-plugin": "^3.2.0",  10          "css-loader": "^2.1.0",  11          "less-loader": "^4.1.0",  12          "sass-loader": "^7.1.0",  13          "style-loader": "^0.23.1",  14          "ts-loader": "^5.3.3",  15          "typescript": "^3.2.2",  16          "webpack": "^4.28.4",  17          "webpack-cli": "^3.2.1",  18          "webpack-dev-server": "^3.1.14"  19      },  20      "scripts": {  21          "watch": "webpack --watch",  22          "build": "webpack"  23      },  24      "keywords": [],  25      "author": "Samet Tarim",  26      "license": "ISC"  27  } 

        Here is, among other things, the line scripts and in which we have the line "build": "webpack" so that we can then with

        Webpack$ USERNAME$ npm run build

        run webpack instead of with

        Webpack$ USERNAME$ npx webpack

        We can add as many as you can see watch is also available. But more on that, because if you would do it now you will only get one mistake.



        Webpack Project Create folders and files

        We now create a folder src / and an index.html and the JavaScript file index.js, we put these two in the same directory src /.


        // HTML CODE
           0  <!DOCTYPE html>  1  <html>  2    3  <head>  4      <meta charset="UTF-8">  5      <title>Webpack</title>  6  </head>  7    8  <body>  9      <script src="./index.js"></script>  10  </body>  11    12  </html> 

          // JS CODE
             0  import './style.css';  1    2  function component() {  3      let element = document.createElement('div');  4      let content = document.createTextNode("Hi there and greetings!");   5      element.appendChild(content);  6      return element;  7    }  8      9    document.body.appendChild(component()); 


            Configuration of the webpack.config.js

            We still need the webpack.config.js, because we can not configure anything else. The configuration makes Webpack so powerful But there is also another alternative solution without configuration and this is named Parcel, but in addition there is also a tutorial. We are installing our loader for CSS Loader and a  Style Loader. Now our package.json should look like below.


            Webpack$ USERNAME$ npm install --save-dev css-loader
            Webpack$ USERNAME$ npm install --save-dev style-loader
            // JSON CODE
               0  {  1      "name": "Webpack",  2      "version": "1.0.0",  3      "description": ",  4      "main": "index.js",  5      "dependencies": {},  6      "devDependencies": {  7          "css-loader": "^2.1.0",  8          "style-loader": "^0.23.1",  9          "webpack": "^4.28.4",  10          "webpack-cli": "^3.2.1",  11      },  12      "scripts": {  13          "test": "echo \"Error: no test specified\" && exit 1",  14      },  15      "keywords": [],  16      "author": ",  17      "license": "ISC"  18  } 

              We now replace one line with another in scripts so we can create our index.bundle.js with npm, which also includes our CSS.


              // JSON CODE
                 0  {  1      "name": "Webpack",  2      "version": "1.0.0",  3      "description": ",  4      "main": "index.js",  5      "dependencies": {},  6      "devDependencies": {  7          "css-loader": "^2.1.0",  8          "style-loader": "^0.23.1",  9          "webpack": "^4.28.4",  10          "webpack-cli": "^3.2.1",  11      },  12      "scripts": {  13          "build": "webpack"   14      },  15      "keywords": [],  16      "author": ",  17      "license": "ISC"  18  } 

                Now let's put the webpack configuration file, which looks like this.


                // JS CODE
                   0  const path = require('path');  1    2  module.exports = {  3      /**  4       * @see https://webpack.js.org/guides/development/  5       */  6      mode: 'development',  7      /**  8       * @see https://webpack.js.org/concepts/  9       */  10      entry: {  11          index: './src/index.js'  12      },  13      /**  14       * @see https://webpack.js.org/concepts/output/  15       */  16      output: {  17          path: path.resolve(__dirname, 'dist'),  18          filename: '[name].bundle.js',  19      },  20      /**  21       * @see https://webpack.js.org/configuration/module/  22       */  23      module: {  24          rules: [  25              {  26                  test: /\.css$/,  27                  use: [  28                      { loader: 'style-loader' },  29                      { loader: 'css-loader' }  30                  ],  31              },  32          ],  33      }  34  }; 

                  You could start now and enter the command now in the console, but then you would have to manually write the index.html in the dist / folder or copy. But try it and you'll see that your index.bundle.js is created in a dist / folder, as we specified in webpack.config.js. Below we create the HTML file dynamically with a plugin.


                  Webpack$ USERNAME$ npm run build
                  // OUTPUT CODE
                  $Webpack USERNAME$ npm run build
                  
                  > webpack@1.0.0 build /Users/worldwantweb/Projects/Sites/VSC/Webpack
                  > webpack
                  
                  Hash: dbab9198e0a4186a823c
                  Version: webpack 4.28.4
                  Time: 903ms
                  Built at: 2019-01-15 22:40:53
                            Asset      Size  Chunks             Chunk Names
                  index.bundle.js  7.01 KiB       0  [emitted]  index
                  Entrypoint index = index.bundle.js
                  [0] ./src/index.js 321 bytes {0} [built]
                  [1] ./src/style.css 1.07 KiB {0} [built]
                  [2] ./node_modules/css-loader/dist/cjs.js!./src/style.css 261 bytes {0} [built]
                      + 3 hidden modules


                  Use Webpack plugins

                  We packed our index.html into the src / folder, we created one because we want to copy it and write it to the dist / folder, but we can also pass a string directly to html. So instead of writing index.html itself in the dist folder, we do it dynamically and we use plugins for that. Here in the example we set that  HTML Webpack Plugin and we enter the following in our console.


                  Webpack$ USERNAME$ npm install --save-dev html-webpack-plugin

                  Did you install the plugin it was added in the package.json and so we can use it now. However, we still have to customize our webpack.config.js.


                  // JS CODE
                     0  const path = require('path');  1  const HtmlWebpackPlugin = require('html-webpack-plugin');  2    3  module.exports = {  4      mode: 'development',  5      entry: {  6          index: './src/index.js'  7      },  8      output: {  9          path: path.resolve(__dirname, 'dist'),  10          filename: '[name].bundle.js',  11      },  12      module: {  13          rules: [  14              {  15                  test: /\.css$/,  16                  use: [  17                      { loader: 'style-loader' },  18                      { loader: 'css-loader' }  19                  ],  20              },  21          ],  22      },  23      /**  24       * @see https://webpack.js.org/plugins/  25       */  26      plugins: [  27          /**  28           * @see https://github.com/jantimon/html-webpack-plugin  29           */  30          new HtmlWebpackPlugin({  31              title: 'Webpack',  32              template: './src/index.html',  33              filename: 'index.html',  34          })  35      ]  36  }; 

                    That's what it looks like and the plugin is also integrated. We can now edit our HTML file and when we run build the changes will be applied. I have now tagged the file with some tags and removed the script tag to dynamically generate this line as well.


                    // HTML CODE
                       0  <!DOCTYPE html>  1  <html>  2    3  <head>  4      <meta charset="UTF-8">  5      <title><%= htmlWebpackPlugin.options.title %></title>  6  </head>  7    8  <body>  9      <div class="wrap">  10          <div class="block">  11              Block  12              <div class="block__element">  13                  Element  14              </div>  15              <div class="block__element block--modifier">  16                  Modified Element  17              </div>  18          </div>  19      </div>  20  </body>  21    22  </html> 

                      So we have created a basis that allows us to edit all of our src and then create our bundles at any time. Now if we execute our build command again then our index.html should also be copied into the dist folder and also our index.bundle.js be added with a script tag in the index.html


                      Webpack$ USERNAME$ npm run build

                      If all of this works then we can now install a plugin to clean the dist / folder with every build command.  Clean up dist Folder, this prevents us from writing something in the HTML file several times. Then we execute our command to install and add our webpack.config.js again and add the plugin.


                      Webpack$ USERNAME$ npm install --save-dev clean-webpack-plugin
                      // JS CODE
                         0  const path = require('path');  1  const HtmlWebpackPlugin = require('html-webpack-plugin');  2  const CleanWebpackPlugin = require('clean-webpack-plugin');  3    4  module.exports = {  5      mode: 'development',  6      entry: {  7          index: './src/index.js'  8      },  9      output: {  10          path: path.resolve(__dirname, 'dist'),  11          filename: '[name].bundle.js',  12      },  13      module: {  14          rules: [  15              {  16                  test: /\.css$/,  17                  use: [  18                      { loader: 'style-loader' },  19                      { loader: 'css-loader' }  20                  ],  21              },  22          ],  23      },  24      plugins: [  25          new HtmlWebpackPlugin({  26              title: 'Webpack',  27              template: './src/index.html',  28              filename: 'index.html',  29          }),  30          new CleanWebpackPlugin(['dist']),  31      ]  32  }; 

                        Now you can run our build command again and your dist / folder will be cleaned up first. Now go to your index.html in the browser and everything should be there HTML, CSS and also JavaScript.

                        That's it then for this tutorial, I'll build on this example building further tutorials where we u.a. start a server after the build process. How to integrate TypeScript and maybe in combination with Babel. We will integrate SASS and LESS as well as separate the configuration files. Or integrate other frameworks and much more.

                        You can also automatically create all files with my generator Webpack Preact and immediately set your project environment to start with the code.
                         Generator Webpack Preact

                        We build this one:
                         Webpack-HTML-CSS-SASS-JavaScript

                        And here one with typescript:
                         Webpack-HTML-CSS-SASS-JavaScript-TypeScript

                        Advertising

                        Your Comment

                        * This fields are required, email don't publish
                        ?

                        This field is optional
                        Fill this field link your name to your website.

                        Data entered in this contact form will be stored in our system to ensure the output of the comment. Your e-mail address will be saved to determine the number of comments and for registration in the future

                        I have read the Privacy policy and Terms. I Confirm the submission of the form and the submission of my data.
                        tnado © 2024 | All Rights Reserved
                        Made with by prod3v3loper