Mik*_*ike 5 reactjs webpack create-react-app dotenv
我有一个项目要从旧版 React 应用程序迁移到标准应用程序create-react-app(未弹出)。
在遗留项目中,它.env使用dotenv和手动加载文件dotenv-expand并通过 webpack 注入DefinePlugin。
create-react-app直观地支持dotenv但只能识别带REACT_APP_前缀的变量。
遗留代码中有很多地方以及使用process.env.xxx变量的其他存储库中的导入包,因此现在不可能在迁移之前用前缀重命名它们。
在这种情况下,如何create-react-app识别没有REACT_APP_前缀的dotenv 变量?
顺便说一句,我rewire之前尝试通过 webpack 进行一些简单的自定义来构建脚本,例如捆绑 js 和 css:
const path = require('path');
const rewire = require('rewire');
const defaults = rewire('react-scripts/scripts/build.js');
let webpackConfig = defaults.__get__('config');
webpackConfig.output.filename = 'static/js/[name].js';
webpackConfig.optimization.splitChunks = { cacheGroups: { default: false } };
webpackConfig.optimization.runtimeChunk = false;
webpackConfig.plugins.find(plugin => plugin.__proto__.constructor.name === 'MiniCssExtractPlugin').options.filename = 'static/css/[name].css';
webpackConfig.plugins.find(plugin => plugin.__proto__.constructor.name === 'MiniCssExtractPlugin').options.moduleFilename = () => 'static/css/[name].css';
Run Code Online (Sandbox Code Playgroud)
但它似乎dotenv并且DefinePlugin更复杂。不确定是否可以以相同的方式实现。
还使用rewire
// "start": "node start.js"
const rewire = require('rewire');
process.env.NODE_ENV = 'development';
let getClientEnvironment = rewire('react-scripts/config/env.js');
getClientEnvironment.__set__(
'REACT_APP',
/(^REACT_APP_|API|DEPLOY|SECRET|TOKEN|URL)/,
);
let configFactory = rewire('react-scripts/config/webpack.config.js');
configFactory.__set__('getClientEnvironment', getClientEnvironment);
let start = rewire('react-scripts/scripts/start.js');
start.__set__('configFactory', configFactory);
Run Code Online (Sandbox Code Playgroud)
build有点不同
// "build": "node build.js"
const rewire = require('rewire');
process.env.NODE_ENV = 'production';
let getClientEnvironment = rewire('react-scripts/config/env.js');
getClientEnvironment.__set__(
'REACT_APP',
/(^REACT_APP_|API|DEPLOY|SECRET|TOKEN|URL)/,
);
let configFactory = rewire('react-scripts/config/webpack.config.js');
configFactory.__set__('getClientEnvironment', getClientEnvironment);
let webpackConfig = configFactory('production');
let build = rewire('react-scripts/scripts/build.js');
build.__set__('config', webpackConfig);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3892 次 |
| 最近记录: |