简体   繁体   English

Webpack中可互换的配置文件

[英]Interchangeable configuration files in Webpack

I'm trying to bundle a react project that can run in multiple environments and needs different configurations to run on each one. 我正在尝试捆绑一个可在多个环境中运行并且需要在每个环境上运行不同配置的React项目。 I have it set up with browserify, but have recently been looking to move to webpack. 我已经使用browserify进行了设置,但是最近一直在寻求迁移到Webpack。

The idea goes like this: there's a js directory with a bunch of js files, of which main.js is the entry point. 这个想法是这样的:有一个js和一帮JS文件,其中的目录main.js的入口点。 There is also a config folder with development.js , staging.js , production.js and so on. 还有一个config文件夹,其中包含development.jsstaging.jsproduction.js等。 I am importing the configuration from all files using import config from './config' . 我正在使用import config from './config'所有文件中import config from './config' So I want to be able to create a main.bundle.js file with all our code, and another config.js whose contents can be replaced with those of {environment}.js . 因此,我希望能够使用我们的所有代码创建一个main.bundle.js文件,以及另一个config.js其内容可以替换为{environment}.js

This allows us to choose the configuration for the app in deploy time , not at build time, just by copying over the contents of {environment.js} . 这使我们能够在部署时而不是在构建时选择应用程序的配置,只需复制{environment.js}的内容即可。

I have attempted to unsuccessfully use webpack's CommonsChunkPlugin , but it complains at bundle time that js/config.js is not there (obviously). 我尝试使用webpack的CommonsChunkPlugin失败,但是它在捆绑时抱怨js/config.js不存在(很明显)。

Why not make multiple builds, one with each config, and then deploy the one you want? 为什么不进行多个构建,每个配置一个,然后部署所需的构建? There's different ways you could load the desired config for the build, but one very way would be to use the DefinePlugin to define constants for each environment, write a conditional against those constants to load the corresponding config, and let the Uglify plugin's dead code elimination pare down the conditional to the one valid case. 有多种方法可以加载所需的配置以进行构建,但一种方法是使用DefinePlugin为每个环境定义常量,针对这些常量编写条件以加载相应的配置,并消除Uglify插件的无效代码将条件缩减为一个有效案例。 I've used this approach in a number of places to handle per-environment conditionals without bloating the production code. 我在许多地方都使用了这种方法来处理每个环境的条件,而不会膨胀生产代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM