首先,我的目标不是浏览器环境,而是Node。
我在单独的文件中有三个顶级React组件。他们使用(要求)其他组件:
Component1.js
React, ReactIntl
Component2.js
React, ReactIntl, ComponentFoo
Component2.js,
React, ReactIntl, ReactToolbox/Dropdown
// Let's say they all quite similar:
const React = require('react');
const ReactIntl = require('react-intl');
const ComponentFoo = require('./ComponentFoo');
const Component1 = React.createClass({
render: function() {
return (
<div>
<ComponentFoo />
</div>
);
}
});
module.exports = Component1;
这意味着他们中的每一个都至少需要React。我希望Webpack将我的三个组件使用的React和其他常用模块移动到另一个文件中。有了它,它必须以这种方式编译我的三个组件,以便他们知道从哪里需要React和其他常见组件:
commonModules.js
React, ReactIntl, ReactToolbox/Dropdown, ComponentFoo, etc...
Component1.js
Component2.js
Component2.js
我想在服务器端要求Component1
,它已经知道从哪里需要它所依赖的一切:
const ReactDOMServer = require('react-dom/server');
const Component1 = require('./../../path/to/compile/component/to/Component1');
const Component1HTML = ReactDOMServer.renderToString(React.createElement(Component1, {
data: data
}));
如何配置Webpack以便它可以接近它?我当前的配置如下,它不起作用。我使用CommonsChunkPlugin
但是如何设置它?我已经设置了target: 'node'
和libraryTarget: 'commonjs2'
:
const path = require('path');
const webpack = require('webpack');
module.exports = {
context: process.cwd(),
entry: {
'path/to/compile/component/to/Component1': './path/from/Component1.js',
'path/to/compile/component/to/Component2': './path/from/Component2.js',
'path/to/compile/component/to/Component3': './path/from/Component3.js',
},
debug: false,
output: {
filename: '[name].js',
path: './',
libraryTarget: 'commonjs2',
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
presets: ["es2015", "stage-0", "react"]
},
},
{
test: /\.scss/i,
loaders: [
'css?modules&importLoaders=1&minimize&localIdentName=[local]_[hash:3]',
'sass?includePaths[]=' + path.resolve(__dirname, "./node_modules/compass-mixins/lib"),
'toolbox'
]
},
],
},
toolbox: {theme: '_theme.scss'},
resolve: {
extensions: ['', '.js', '.jsx', '.react', '.scss', '.json'],
},
devtool: "eval",
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ["commons"],
filename: "assets/js/react/prod/[name].js",
minChunks: 2,
children: true,
}),
],
target: 'node',
};