Webpack外部节点和浏览器

我有一个在浏览器和服务器上运行的同构React应用程序。 我通过两个不同的入口点和不同的configuration运行两个单独的Webpack构build,为两者构build相同的代码。

问题是,在服务器的节点上运行时,通过外部脚本标记(本例中为Google Maps)存在于浏览器窗口上的外部文件显然不存在。 除入口点文件外,代码是相同的。

index.html的:

// index.html <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXX"></script> 

简化configuration:

 // 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' 

我目前有一个我一点都不喜欢的解决scheme。

 // 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将模块replace为noop,按照Dustan Kasten的想法:

 { plugins: [ new webpack.NormalModuleReplacementPlugin(/^google$/, 'node-noop'), ], }