2

我最近从 Webpack 4 更新到 Webpack 5,早些时候我在 window 对象上有一个函数index.js,它看起来像

index.js

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

当它被捆绑时,我可以在文件index.js中找到相同的功能。common.bundle.js

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>

在控制台中,当我键入在 Webpack 4 中按预期工作ReferenceError: someFunction is not defined 时,我无法在 chrome 控制台中打印函数定义。window.someFunction

如何将我的函数附加到 Webpack 5 中的窗口对象,以及如何访问它?

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

3 回答 3

1

尝试将 node.global: true 添加到您的配置中:

node: {
  global: true
}

于 2021-08-27T08:25:30.990 回答
1

DoneDel0 的评论对我来说是正确的解决方案。

node: {
  global: true
}

这背后的原因是 webpack 5 不再包含用于节点模块的 polyfill,因此您必须手动设置每个。

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

但是值得注意的是,文档确实建议使用 ProvidePlugin 而不是全局的。

于 2021-10-29T00:06:03.037 回答
0

感谢您的回答,这个问题原来是由于缺少节点核心模块的 polyfills。

在我的情况下,我必须提供 polyfill 才能process使用ProvidePlugin.

我通过在我的配置中添加以下内容来做了同样的事情

new webpack.ProvidePlugin({
    process: "process/browser",
})
于 2022-01-15T15:19:16.737 回答