2017-07-16 68 views
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') 
); 
+0

如果你有一个模块中声明的一些价值观,为什么你不只是导入? (我错过了什么?) –

+0

我希望这些值由(之前的)构建步骤生成。和in一样,properties.json将被动态填充,而不是硬编码。 – pisomojado

+1

你在找什么是https://webpack.js.org/plugins/define-plugin/ – azium

回答

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'));