【问题标题】:Why would webpack output with global `self` instead of `this` when output.globalObject: "this" is specified?当指定 output.globalObject: "this" 时,为什么 webpack 会使用全局 `self` 而不是 `this` 输出?
【发布时间】:2021-06-07 13:13:21
【问题描述】:

我正在使用 webpack-cli 4.7.0。我有一个库,我想为两种不同的环境编译,一个用于 web,一个用于 node。根据this documentation,这很容易实现,我从 webpack.config.js 导出两个单独的有效 webpack 配置。

所以我创建了两个有效的 webpack 配置,一个用于服务器,一个用于客户端。 Webpack 按指定输出两个单独的文件,但坚持使用“self”而不是“this”,即使我在配置中指定了output.globalObject: "this"。如果我理解official documentation,则不应该是这样。

webpack.config.js

const path = require( "path" );
// const webpack = require( "webpack" );


const serverConfig  = {
    mode: "production",
    entry: "./src/Check4.js",
    target: "node",
    output: {
        path: path.resolve( __dirname, "dist" ),
        filename: "Check4.node.js",
        globalObject: "this",
        library : {
            type: "commonjs2",
            export: "default"

        }

    }
};

const clientConfig  = {
    mode: "production",
    entry: "./src/Check4.web.js",
    target: "web",
    output: {
        path: path.resolve( __dirname, "dist" ),
        filename: "Check4.js",
        globalObject: "this",
        library : {
            name: "Check4",
            type: "window",
        }
    }
};

module.exports = [serverConfig, clientConfig];

作为参考,这里是 webpack 输出的前几个字节,表明它使用的是全局“self”而不是“this”

(()=>{var e={172:e=>{self,e.exports=(()=>{"use strict";var e={502:...

【问题讨论】:

    标签: node.js webpack compilation global-object


    【解决方案1】:

    答案在我的依赖项中。我写了一个这个类所依赖的类。父类没有编译,所以 webpack 试图同时编译。

    几个小时后,我偶然发现了这一点,这导致我解决了这个问题。 https://github.com/markdalgleish/static-site-generator-webpack-plugin/issues/79

    嘿,更新;环顾一圈后,对我来说,这看起来像 错误来自同构获取依赖项 (https://github.com/matthew-andrews/iso…)。看起来类似于文档 没有定义人们遇到的问题,因为这个预渲染 不会发生在浏览器上下文中。我没有更多的时间 今天看看它为什么会这样或解决方案,但那是 我的预感。检查你的 polyfill 和依赖项。

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 1970-01-01
      • 2013-12-30
      • 2016-04-06
      • 2016-07-08
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多