简体   繁体   English

将 function 附加到 window object 在 ZC64E0F7D4E01E48E693C9C5638B5E 中

[英]Attaching a function to window object in Webpack 5

I recently updated to Webpack 5 from Webpack 4, earlier I had a function on window object in index.js such that it looked something like I recently updated to Webpack 5 from Webpack 4, earlier I had a function on window object in index.js such that it looked something like

index.js index.js

window.someFunction = function (...arguments) {
    // function body
}

when this index.js gets bundled I can find this same function in common.bundle.js file.当这个index.js被捆绑时,我可以在common.bundle.js文件中找到同样的 function。

and my index.html looks something like this我的index.html看起来像这样

index.html索引.html

<head>
    // rest of the head stuff
    <script src="./dist/common.bundle.js"></script>
</head>
<body>
    <script type="text/javascript">
        someFunction(); // calling someFunction from the window object
        // Also tried using window.someFunction() still doesn't work    
    </script>
</body>

In console I get ReferenceError: someFunction is not defined and I am not able to print the function defination in chrome console when I type window.someFunction which was working in Webpack 4 as expected.在控制台中我得到ReferenceError: someFunction is not defined并且当我输入window.someFunction时,我无法在 chrome 控制台中打印 function 定义,它在 ZC64E0F7D4E01E48E6937ZBFC45 中按预期工作。

How do I attach my functions to window object in Webpack 5, and how do I go about accessing it?如何在 Webpack 5 中将我的功能附加到 window object,以及如何访问它?

webpack.config.js webpack.config.js

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

module.exports = (env) => {
  return {
    mode: "development",
    devtool: "source-map",
    entry: {
      common: "./index.js",
    },
    output: {
      pathinfo: true,
      path: path.join(__dirname, "dist"),
      filename: "[name].bundle.js",
    },
    plugins: [
      new webpack.DefinePlugin({
        "process.env.NODE_ENV": JSON.stringify("development"),
      }),
    ],
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: "babel-loader",
            options: {
              cacheDirectory: true,
              babelrc: false,
              presets: [
                [
                  "@babel/env",
                  {
                    modules: false,
                    loose: true,
                    targets: {
                      browsers: [">0.25%", "not ie 11", "not op_mini all"],
                    },
                  },
                ],
                "@babel/react",
              ],
              plugins: [
                [
                  "@babel/plugin-proposal-class-properties",

                  {
                    loose: true,
                  },
                ],
                ["@babel/plugin-transform-runtime"],
              ],
            },
          },
        },
        {
          test: /\.css$/,
          include: /node_modules/,
          use: [{ loader: "style-loader" }, { loader: "css-loader" }],
        },
      ],
    },
    resolve: {
      extensions: [".js", ".jsx"],
      modules: [path.resolve(__dirname, "node_modules")],
      fallback: {
        buffer: false,
        fs: false,
        tls: false,
        net: false,
        path: false,
        zlib: false,
        http: false,
        https: false,
        stream: false,
        crypto: false,
      },
    },
    optimization: {
      // namedModules: true,
      // namedChunks: true,
      minimize: false,
      // minimizer: [new TerserPlugin()],
      runtimeChunk: "single",
      moduleIds: "deterministic",
      chunkIds: "deterministic",
      nodeEnv: "development",
      flagIncludedChunks: false,
      concatenateModules: false,
      splitChunks: {
        hidePathInfo: false,
        minSize: 20000,
        maxAsyncRequests: Infinity,
        maxInitialRequests: Infinity,
        chunks: "all",
        // maxSize: 0,
        minChunks: 1,
        automaticNameDelimiter: "~",
        cacheGroups: {
          commons: {
            test: /[\\/]node_modules[\\/]/,
            name: "other.bundle",
            chunks: "all",
            minChunks: 2,
          },
          defaultVendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
          },
          default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true,
          },
        },
      },
      emitOnErrors: true,
      checkWasmTypes: false,
      removeAvailableModules: false,
    },
    performance: {
      hints: "warning",
    },
    stats: {
      all: false,
      assets: true,
      builtAt: true,
      cachedAssets: false,
      cachedModules: true,
      chunkGroups: true,
      colors: true,
      env: true,
      errors: true,
      hash: true,
      logging: "info",
      timings: true,
      modules: true,
      outputPath: true,
      performance: true,
      errorsCount: true,
      warnings: false,
      warningsCount: true,
      publicPath: true,
      reasons: true,
      ids: true,
      version: true,
    },
    cache: {
      type: "filesystem",
      version: "1.0.0",
      store: "pack",
      name: "AppBuildCache",
      maxMemoryGenerations: 1,
      idleTimeout: 60000,
      idleTimeoutAfterLargeChanges: 1000,
      idleTimeoutForInitialStore: 0,
      hashAlgorithm: "md4",
      cacheLocation: path.resolve(__dirname, ".cache"),
    },
    externals: [
      {
        react: "React",
        "react-dom": "ReactDOM",
        jquery: "jQuery",
      },
    ],
  };
};

Try to add node.global: true to your config:尝试将 node.global: true 添加到您的配置中:

 node: { global: true }

DoneDel0's comment was the correct solution for me. DoneDel0 的评论对我来说是正确的解决方案。

node: {
  global: true
}

The reasoning behind this is webpack 5 does no longer include a polyfills for node modules, so you have to manually set each.这背后的原因是 webpack 5 不再包含节点模块的 polyfill,因此您必须手动设置每个。

https://webpack.js.org/configuration/node/#nodeglobal https://webpack.js.org/configuration/node/#nodeglobal

However its good to note that the docs does suggest using ProvidePlugin instead of global.然而,值得注意的是,文档确实建议使用 ProvidePlugin 而不是 global。

Thank you for the answers, the issue turned out exactly to be due to missing polyfills for node core modules.感谢您的回答,这个问题原来是由于缺少节点核心模块的 polyfills。

In my case the I had to provide polyfill for process using ProvidePlugin .在我的情况下,我必须使用 ProvidePlugin 为process提供ProvidePlugin

I did the same by adding below to my config我通过在我的配置中添加以下内容来做了同样的事情

new webpack.ProvidePlugin({
    process: "process/browser",
})

I added我添加了

node: {
  global: true
}

but still the function is undefined in window object.但 function 在 window object 中仍然未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM