2017-07-16 105 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')); 
相關問題