node.js - Node 和浏览器中的 Webpack 外部

标签 node.js reactjs webpack isomorphic-javascript

我有一个在浏览器和服务器上运行的同构 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/

相关文章:

node.js - 如何使用 npm 脚本获取 shell 脚本?

javascript - 在 React 中读取 CSV 文件

css - Tailwind 的 theme() 无法识别

reactjs - React/redux,显示多个组件,共享相同的操作,但具有不同的状态

webpack - 如何使用webpack为index.html中的js和css导入添加URL前缀?

twitter-bootstrap-3 - 使用 webpack for vue 加载 Bootstrap

node.js - Heroku 上的 Node 应用程序由于只读文件系统而失败

node.js - 为 Gitlab CI Dockerizing Nodejs 依赖

java - NodeJs使用pbkdf2Sync加密并在java中解密

javascript - 奇怪的(webpack?)错误 "TypeError: Object(...) is not a function"