Webpack how to build production code and how to use it

前端 未结 8 925
梦谈多话
梦谈多话 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)

    0 讨论(0)
  • 2020-11-29 15:56

    If you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isProd to activate certain features only in certain situations and only have a single webpack.config.js file.

    const isProd = (process.env.NODE_ENV === 'production');
    
     if (isProd) {
         plugins.push(new AotPlugin({
          "mainPath": "main.ts",
          "hostReplacementPaths": {
            "environments/index.ts": "environments/index.prod.ts"
          },
          "exclude": [],
          "tsConfigPath": "src/tsconfig.app.json"
        }));
        plugins.push(new UglifyJsPlugin({
          "mangle": {
            "screw_ie8": true
          },
          "compress": {
            "screw_ie8": true,
            "warnings": false
          },
          "sourceMap": false
        }));
      }
    

    By the way: The DedupePlugin plugin was removed from Webpack. You should remove it from your configuration.

    UPDATE:

    In addition to my previous answer:

    If you want to hide your code for release, try enclosejs.com. It allows you to:

    • make a release version of your application without sources
    • create a self-extracting archive or installer
    • Make a closed source GUI application
    • Put your assets inside the executable

    You can install it with npm install -g enclose

    0 讨论(0)
提交回复
热议问题