2
我需要在我的視圖(html文件)中呈現React組件。我正在使用webpack 1並且得到了component undefined
的錯誤。我試圖使用window.component,但它沒有工作。如果我在組件內部使用RenderDOM,則一切正常。在html腳本標記中未定義React組件
我的組件:
export class SmallCart extends BaseComponent {
...
render() {...}
}
的WebPack 1配置:
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var BowerWebpackPlugin = require('bower-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: {
...
myComponent: "./wwwroot/js/es6/SmallCart/SmallCart.jsx",
...
},
output: {
path: __dirname + "/dist",
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
module: {
loaders: [
{
test: /\.(png|jpg|gif|ico)$/,
loader: "file-loader?name=assets/[name]-[hash:6].[ext]"
}, {
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&minetype=application/font-woff&name=assets/[name]-[hash:6" +
"].[ext]"
}, {
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader?name=assets/[name]-[hash:6].[ext]"
}, {
test: /\.scss$/i,
loader: ExtractTextPlugin.extract(['css-loader?-autoprefixer!postcss-loader', 'sass'])
}, {
test: /\.css$/i,
loader: ExtractTextPlugin.extract(['css-loader?-autoprefixer!postcss-loader'])
}, {
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
progress: true,
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.json', '.js']
},
externals: {
jquery: "jQuery",
react: "React",
reactDOM: "ReactDOM"
},
plugins: [
new webpack.ProvidePlugin({'window.Nette': 'nette-forms', 'window.jQuery': 'jquery', jQuery: 'jquery', $: 'jquery'}),
new webpack
.optimize
.CommonsChunkPlugin({
filename: "commons.js", name: "commons",
}),
new ExtractTextPlugin("frontend.css"),
]
}
在我看來,我有這樣的:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.js" charset="utf-8"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.min.js" charset="utf-8"></script>
<script type="text/javascript" src="/dist/commons.js" charset="utf-8"></script>
<script type="text/javascript" src="/dist/SmallCart.js" charset="utf-8"></script>
<script type="text/javascript">
window.data_for_react = {};
ReactDOM.render(React.createElement(SmallCart, { dataSource : data_for_react}, document.getElementById('box-to-rendering')));
</script>
但是在渲染方法中,組件是未定義的。 有什麼不對?是否有可能呈現組件?
謝謝您的時間。
編輯
好了,現在我嘗試用window.SmallBasket和配置的WebPack更新:
...
new webpack
.optimize
.CommonsChunkPlugin({
names: [
"commons"
],
minChunks: Infinity
}),
...
和它的作品。但是如果沒有窗戶屬性,我仍然無法解決它。
謝謝你的評論。我試過了,但仍然得到'Uncaught ReferenceError:SmallCart is not defined' –
嘗試使用 加載它? –
OneNeptune
使用JSX和babel語法?或者你是什麼意思? –