从 webpack 缩小中排除模块

Exclude module from webpack minification

我们在单页应用程序中使用 WebPack。该应用程序被部署到许多环境中。我们有一个要求,应用程序需要在给定环境中调用特定端点。

为了给给定环境提供端点地址,需要一个环境模块。这是当前的解决方案(有很多,这不是问题的重点)。但是,我们需要将 config.js 从缩小中排除,以便它可以作为部署过程的一部分被覆盖。

config.js 如下所示:

module.exports = {
    env: {
        endpointUrl: 'http://1.2.3.4',
        authUrl: 'http://5.6.7.8'
    }
};

并使用以下内容进行引用:

const endpointUrl = config.env.endpointUrl;
const authUrl = config.env.authUrl;

WebPack 配置如下所示:

var webpack = require('webpack');
​
module.exports = {
    entry: {
        main: './src/js/main.jsx',
        login: './src/js/login-main.jsx'
    },
    output: {
        path: __dirname + '/dist',
        filename: '[name].bundle.js'
    },
    devtool: 'source-map',
    module: {
        loaders: [{
            test: /.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            plugins: ['transform-react-jsx'],
            query: {stage: 0}
        }, {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'eslint-loader'
        }]
    },
    plugins: [
        new webpack.ProvidePlugin({
            fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch'
        }),
        new webpack.DefinePlugin({
            __DEV__: JSON.stringify(JSON.parse(process.env.DEV || false))
        })
    ]
};

到目前为止,我们已经查看了 externals and module loaders,但还没有找到任何有效的方法。模块加载器中的排除仍然导致模块被缩小。

我们看过的一些 SO 问题:

我认为 uglify-loader 可能会成功。与开箱即用相比,它可以让您更好地控制缩小结果。

Webpack externals 是避免捆绑某些依赖项的好选择。

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

将依赖项添加为外部依赖项不仅会将其排除在缩小之外,甚至不会被 webpack 解析。

webpack.config.js

var webpack = require('webpack');

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

将用于要求您的 config.js 的路径添加为外部路径。在我的简单示例中,路径对应于 ./config。将它关联到将包含您的配置对象的全局变量。在我的例子中,我只是使用 config 作为变量名(见下文 config.js)。

index.js

const config = require('./config');

const endpointUrl = config.env.endpointUrl;
const authUrl = config.env.authUrl;

console.log(endpointUrl);
console.log(authUrl);

由于您阻止 webpack 解析 config.js 模块,因此它必须在运行时在环境中可用。一种方法是将其公开为全局上下文中的 config 变量。

config.js

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

然后您可以为任何给定环境加载特定的 config.js 文件。

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>