0
我想要做的事情非常简单:我正在构建一个React应用程序,并使用webpack将其绑定。我有一些想要通过配置JSON文件传递的属性,并且能够在我的React代码中引用这些值。Webpack + React:将任意键值配置数据传递给JSX
我想出了一个办法,但似乎应该有一个更直接的方法来做到这一点。寻求如何更干净的建议。
这是我正在做的简化版本,它的工作原理。
这个想法是,我将这个值线程化为一个隐藏的HTML元素,然后将它作为道具传递到我的主React元素中。我更喜欢将这个值直接传递给React道具的方法,但是还没有找到办法做到这一点。
properties.json
{
"myKey": "foo (possibly dynamically generated by a build step)"
}
webpack.config.js
const config = require(__dirname + '/properties.json');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body',
metadata: config
});
// ... Rest of normal-looking webpack with babel-loader and react preset
的index.html
<html>
<head><!-- normal head contents --></head>
<body>
<!-- One of these per key-value pair in my properties -->
<div id="config-myKey" style="display: none">
<%= htmlWebpackPlugin.options.metadata.myKey %>
</div>
<div id="app"></div>
</body>
</html>
React app(index.js):
const Main = React.createClass({
render: function() {
return(<p>This is the value for myKey: ${this.props.myKey}</p>);
}
});
// Read in the value from the hidden HTML element, and pass it through to the
// React app as props. This part feels like there should be a better way to
// do it.
const myValue = document.getElementById('config-myKey').innerHTML.trim();
ReactDOM.render(
<Main myKey=${myValue}/>,
document.getElementById('app')
);
如果你有一个模块中声明的一些价值观,为什么你不只是导入? (我错过了什么?) –
我希望这些值由(之前的)构建步骤生成。和in一样,properties.json将被动态填充,而不是硬编码。 – pisomojado
你在找什么是https://webpack.js.org/plugins/define-plugin/ – azium