Webpack + React:将任意键值配置数据传递到JSX

时间:2017-07-16 13:03:11

标签: reactjs webpack jsx

我想要做的非常简单:我正在构建一个React应用程序,使用webpack捆绑它。我有一些想要从配置JSON文件传递的属性,并且能够在我的React代码中引用这些值。

我想出了一种方法,虽然似乎应该有更直接的方法来做到这一点。寻找关于如何更干净地做到这一点的建议。

这是我正在做的简化版本,并且有效。

我的想法是,我将此值线程化为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')
);

1 个答案:

答案 0 :(得分:0)

结果DefinePlugin正是我想要的。谢谢@azium。

为了完整起见,这就是我现在的工作方式。更干净。

<强> properties.json 即可。注意转义的报价;这些是必要的,因为我希望它显示为字符串文字。

{
  "REPLACE_ME_WITH_FOO_VALUE": "\"foo\""
}

<强> webpack.config.js

const config = require(__dirname + '/properties.json');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
   template: __dirname + '/app/index.html',
   filename: 'index.html',
   inject: 'body'
});
const DefinePlugin = new webpack.DefinePlugin(config);

module.exports = {
   entry: [ './app/index.js' ],

   // ... Rest of normal-looking webpack with babel-loader and react preset

   plugins: [HTMLWebpackPluginConfig, DefinePlugin]
});

<强> index.js

const myValue = REPLACE_ME_WITH_FOO_VALUE;
ReactDOM.render(<Main myKey={myValue}/>, document.getElementById('app'));