Webpack how to build production code and how to use it

前端 未结 8 1053
梦谈多话
梦谈多话 2020-11-29 15:06

I am very new to webpack, I found that in production build we can able to reduce the size of overall code. Currently webpack builds around 8MB files and main.js around 5MB.

8条回答
  •  天命终不由人
    2020-11-29 15:56

    Just learning this myself. I will answer the second question:

    1. How to use these files? Currently I am using webpack-dev-server to run the application.

    Instead of using webpack-dev-server, you can just run an "express". use npm install "express" and create a server.js in the project's root dir, something like this:

    var path = require("path");
    var express = require("express");
    
    var DIST_DIR = path.join(__dirname, "build");
    var PORT = 3000;
    var app = express();
    
    //Serving the files on the dist folder
    app.use(express.static(DIST_DIR));
    
    //Send index.html when the user access the web
    app.get("*", function (req, res) {
      res.sendFile(path.join(DIST_DIR, "index.html"));
    });
    
    app.listen(PORT);
    

    Then, in the package.json, add a script:

    "start": "node server.js"
    

    Finally, run the app: npm run start to start the server

    A detailed example can be seen at: https://alejandronapoles.com/2016/03/12/the-simplest-webpack-and-express-setup/ (the example code is not compatible with the latest packages, but it will work with small tweaks)

提交回复
热议问题