簡體   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

index.js

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

當這個index.js被捆綁時,我可以在common.bundle.js文件中找到同樣的 function。

我的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>

在控制台中我得到ReferenceError: someFunction is not defined並且當我輸入window.someFunction時,我無法在 chrome 控制台中打印 function 定義,它在 ZC64E0F7D4E01E48E6937ZBFC45 中按預期工作。

如何在 Webpack 5 中將我的功能附加到 window object,以及如何訪問它?

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",
      },
    ],
  };
};

嘗試將 node.global: true 添加到您的配置中:

 node: { global: true }

DoneDel0 的評論對我來說是正確的解決方案。

node: {
  global: true
}

這背后的原因是 webpack 5 不再包含節點模塊的 polyfill,因此您必須手動設置每個。

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

然而,值得注意的是,文檔確實建議使用 ProvidePlugin 而不是 global。

感謝您的回答,這個問題原來是由於缺少節點核心模塊的 polyfills。

在我的情況下,我必須使用 ProvidePlugin 為process提供ProvidePlugin

我通過在我的配置中添加以下內容來做了同樣的事情

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

我添加了

node: {
  global: true
}

但 function 在 window object 中仍然未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM