20. webpack-version 3

home

Contents

20.1 When to use it.

20.2 First app, build, test

-------------- build -----------------------

          code as below:
          // package.json,    modify
          "scripts" {
              "build": "webpack"
          },
   
          // create webpack.config.js under the app folder, add code as below:
          module.exports = {
             entry:   "./app.js",         // under the app folder
             output: {
                filename: "bundle.js"     // default is app folder
             }    
          }  

            // add app.js under the app folder
            console.log("app loaded")   
            
// under the root, add index.html <html> <body> <h1>home</h1> <script src="bundle.js"></script> </body> </html>

20.3 webpack dev server

        // code
        // continue from the previous lab
        // step 1:   
        npm install webpack-dev-server --save-dev

        // step 2:  in package.json    in key scripts, adding
        "dev": "webpack-dev-derver"

        // step 3:  in webpack.config.js      adding a new key
        devServer: {
             contentBase: __dirname    // using the bundle file under the root,
             port: 8080
        }
            

20.4 partition of js files

       // create the folder structure as below:
       
       | src
           index.js
           another.js
       | dist
           index.html
       
       ---  /src/another.js  ---
       var greeting = "happy new year 2018"
       document.write(greeting)

       ---  /src/index.js  ----
       
       require("./another.js")     
             // under the same folder, src
             // require is a nodejs builtin function
       
       var arr = ['peter', 'tairo', 'emi']
       document.write("from " + arr)

       ---  webpack.config.js ----------
        var path = require("path")
        module.exports = {
            entry: "./src/index.js",

            output: {
                filename: "bundle.js",
                path: path.join(__dirname, "dist")
            },

            devServer:{
                contentBase: path.join(__dirname, "dist"),
                port: 8080
            }
        }
        ---- package.json  ------
         "scripts": {
             "dev": "wepack-dev-server",
             "build": "webpack"
          },
           

20.5 managing folders and files

       // create the folder structure as below:
       
       | js
           app.js
       | public
           index.html   
       
       ---  /js/app.js   ---
       document.write("hello world")
       console.log("app loaded")

       ---  webpack.config.js  ----
       var path = require("path")
       module.exports = {
           
           // --------------------------------
           // for app.js, set the folder to js
           // array is used for multiple bundle files
           
           context: path.resolve("js"), 
           entry: ["./app"],
           
           
           // --------------------------------
           // Key path is the physical folder address.
           // if the folder is not there, it will be created.
           // Key publicPath is for access.
             
           output: {
                 path: path.resolve('build/js/'),
                 publicPath: '/public/assets/js/',
                 filename: "bundle.js"
            },
            
           // --------------------------------
           // index.html is under folder public.
             
            devServer:{
                 contentBase: "public",
                 port: 8080
            },
        }
            
--- /public/index.html --- <html><body> <h1>terst at 3:10 pm</h1> <script src="/public/assets/js/bundle.js"></script>" </body></html>
         ---- package.json  ------
         "scripts": {
             "dev": "wepack-dev-server",
             "build": "webpack"
          },
            

20.6 Multiple bundles

---- index.html ------------ ---- replace tag h1 content for other two ----- <html> <body> <div> <a href="index.html">Home</a> <a href="service.html">Service</a> <a href="contact.html">Contact</a> </div> <h1>Home page</h1> <script src="/public/assets/js/home.js"></script> </body> </html>
         -----      index.js
         ----       replace the content for other two -----
         console.log('App loaded')

        -------     webpack.config.js  -----------------------
        var path = require("path")
        module.exports = {
            context: path.resolve("js"),  
                  
            entry: {                           // the contents is an object
                service: './service.js',       //         it is not an array
                home: './home.js',             // item key name like home is used for output
                contact: './contact.js'
            },
            
            output: {
                path: path.resolve('build/js/'),
                publicPath: '/public/assets/js/',
                
                filename: "[name].js"          // it is an template
                
            },
            devServer:{
                contentBase: "public",
                port: 8080
            }
        }
            

20.7 UglifyJS, webpack plug in - 1

During the development streamline with webpack3, this plugin will be plugged in at later stage.

20.8 ProvidePlugin, webpack plug in - 2

During the development streamline with webpack3, this plugin will be plugged in at an earlier stage.

index.html, add code as below: <div id="div1">default content 1</div> <div id="div1">default content 1</div>

20.9 javascript version 6, loader-1

    // step 1: install related packages
    npm install babel-loader babel-core babel-preset-env --save-dev

    // step 2: add code in webpack.config.js
    module: {
            rules: [
                {
                    test: /.js$/,                // filtering
                    exclude: /(node_modules)/,
                    use: {
                        loader: "babel-loader",  // loader - transform and load them into the js bundle file to reduce http requests
                        options: {
                            presets: ["env"]     // for langauge transformation AND react
                        }
                    }
                }
            ]
        }
        
        note-1: key test is for filtering process.
        note-2: allowing file with js extension.
        note-3: two // is the syntax for javascript regular expression.
        note-4: sometimes, \ is added as an escape character.
        
    // step 3: under app root folder, create a new file .babelrc
    {
        "preset": "env"
    }
    // step 4: npm run build
    open and examine the bundle file
    
    - keyword const(for javascript version 6) is changed to var.
    - One line of code is added for the top. "use strict"
    - Two changes are required by plain javascript.
    - Keyword const means that the object is not mutable. No listening is needed.
    - String literal, "use strict" means to declaring a variable is needed, before it is used..
    

    // step 5: test
    - npm run dev
    - open the browser, localhost:8080, see the same result page
            

20.10 react, loader-2

// step 1: install related packages npm install babel-preset-react --save-dev npm install react react-dom --save verify in package.json // step 2: index.html add one html tag <div id="react-container"></div>
    // step 3:   app.js        replace the code as below:
    
    import React from "react"          // import is a javascript satement
    import ReactDom from "react-dom"
    
            
const MyComponent = () => <h1>hello react</h1> ReactDom.render(<MyComponent />, document.getElementById("react-container")) // step 4: add "react" to key presets for both webpack.config.js and .babelrc ["env", "react"] // step 5: start the server, npm run dev, then start the browser, localhost:8080 you see the page, with the message, "hello react"

20.11 css, loader-3

// step 1: create an app Create an app by cloning from the app for 20.10

    // step 2:  under the root, add style.css
    h1 {
       color: #FF0000;
    }
        

    // step 3:   app.js        add one line of code as below:
    import "./style.css"
        
// step 4: install loaders npm install style-loader css-loader --save-dev // step 5: webpack.config.js add one item as below rules: [ {... }, { test: /\.css$/, use: [ {loader: "style-loader"}, {loader: "css-loader"} ] } ] // step 6: test start the server: npm run dev launch the browser: localhost:8080 to see red color for h1 tags
        // the same for images
        {
		test: /\.jpg$/,
		use: [
			{loader: "url-loader"}
		]    
         }  
		 

20.12 commons chunk bundle

// home.js // index.html <div id="react-container"></div> needed // code the same for service.js, contact.js, change the contents a bit. import React from "react" import ReactDom from "react-dom" const MyComponent = () => <h1>hello from home.js </h1> ReactDom.render(<MyComponent />, document.getElementById("react-container")) // npm run dev, localhost:8080 to see the page from reactjs.

        // in webpack.config.js   add item under module.exports
        plugins: [
            new webpack.optimize.CommonsChunkPlugin({
                name: "commons",
                filename: "commons.bundle.js"
            })
        ]
            

---- adding the shared bundle before a page bundle like below ---

<html> <body> <div> <a href="index.html">Home</a> <a href="service.html">Service</a> <a href="contact.html">Contact</a> </div> <h1>Home page</h1> <div id="react-container"></div> <script src="/public/assets/js/commons.bundle.js"></script> <script src="/public/assets/js/home.js"></script> </body> </html>