我有一个在浏览器和服务器上运行的同构 React 应用程序。我通过两个不同的入口点和不同的配置运行两个单独的 Webpack 构建来为两者构建相同的代码。
问题在于,当在服务器上的 Node 中运行时,通过外部脚本标记(在本例中为 Google map )存在于浏览器窗口中的外部文件显然不会存在。除入口点文件外,代码完全相同。
index.html:
// index.html
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXX"></script>
简化配置:
// Server Webpack config
{
entry: 'server.js',
target: 'node',
externals: {
google: google
}
}
// Client Webpack config
{
entry: 'client.js',
target: 'browser',
externals: {
google: google
}
}
组件:
// The view which builds and runs fine in
// the client but doesn't run on the server.
var React = require('react'),
css = require('./style.css'),
google = require('google'); // Nope, not on the server obviously!
var Component = React.createClass({
render: function () {
return (
<div>
// Do maps stuff
</div>
);
}
});
module.exports = Component;
我的问题是我该如何处理?
Error: Cannot find module 'google'
我目前有一个我一点都不喜欢的解决方案。
// Server Webpack config
{
entry: 'server.js',
target: 'node',
externals: {
google: google
},
plugins: [
new webpack.DefinePlugin({ 'ENV.browser': false }),
]
}
// Client Webpack config
{
entry: 'client.js',
target: 'browser',
externals: {
google: google
},
plugins: [
new webpack.DefinePlugin({ 'ENV.browser': true }),
]
}
// The component
var React = require('react'),
css = require('./style.css');
if (ENV.browser) {
var google = require('google');
}
var Component = React.createClass({
render: function () {
return (
<div>
if (ENV.browser) {
// Do maps stuff
}
</div>
);
}
});
module.exports = Component;
最佳答案
您可以使用 NormalModuleReplacementPlugin
将模块替换为 noop,根据 Dustan Kasten 中的想法:
{
plugins: [
new webpack.NormalModuleReplacementPlugin(/^google$/, 'node-noop'),
],
}
关于node.js - Node 和浏览器中的 Webpack 外部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30246519/