Exclude module from webpack minification

前端 未结 2 737
抹茶落季
抹茶落季 2020-12-05 10:10

We are using WebPack in a single page application. The application is deployed to many environments. We have a requirement where the application needs to call a specific end

相关标签:
2条回答
  • 2020-12-05 10:45

    I think uglify-loader might do the trick. It provides you more control over the minification result than what you get out of the box.

    0 讨论(0)
  • 2020-12-05 10:46

    Webpack externals are a good option to avoid bundle certain dependencies.

    However we need to exclude the config.js from minification so that it can be overwritten as part of the deployment process.

    Adding a dependency as external not only excludes it from minification but it is not even resolved by webpack.

    webpack.config.js

    var webpack = require('webpack');
    
    module.exports = {
      entry: {
        index: './src/index.js'
      },
      output: {
        path: './dist',
        filename: 'bundle.js'
      },
      externals: {
        './config': 'config'
      }
    };
    

    Add as external the path used to require your config.js. In my simple example the path corresponds to ./config. Associate it to the global variable that will contain your configuration object. In my case I just used config as the variable name (see below config.js).

    index.js

    const config = require('./config');
    
    const endpointUrl = config.env.endpointUrl;
    const authUrl = config.env.authUrl;
    
    console.log(endpointUrl);
    console.log(authUrl);
    

    As you are preventing webpack to resolve the config.js module then it has to be available in the environment during runtime. One way could be to expose it as a config variable in the global context.

    config.js

    window.config = {
      env: {
        endpointUrl: 'http://1.2.3.4',
        authUrl: 'http://5.6.7.8'
      }
    };
    

    Then you can load a specific config.js file for any given environment.

    index.html

    <!DOCTYPE html>
    <html>
    <head>
      <title>Webpack</title>
    </head>
    <body>
      <script type="text/javascript" src="config.js"></script>
      <script type="text/javascript" src="dist/bundle.js"></script>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题