首页 > 解决方案 > __webpack_require__ 未定义。这里地图包不起作用

问题描述

尝试使用“@here/maps-api-for-javascript”时,我在网络工作者内部遇到了问题。

我的想法是因为 webpack 更改了在 webworker 中运行的代码。

捆绑包的初始部分(mapsjs.bundle.js): e = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {};

webpack构建后: e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof __webpack_require__.g?__webpack_require__.g:"undefined"

在这种情况下,在 webworker 内部我们没有__webpack_require__变量。看起来我必须配置 webpack 来防止它。

来自官方网站的示例也不起作用。同样的错误。https://developer.here.com/documentation/maps/3.1.22.0/dev_guide/topics/get-started-bundling.html

但是在我们将 here-maps API 添加为 html 中的内联脚本时,一切正常。

标签: reactjswebpackhere-api

解决方案


问题在于 Webpack 5 现在默认重命名“全局”变量。该指南是在 webpack 4 是主要版本时编写的。webpack.config中的以下选项可以解决问题。

node: { global: false }

这个 webpack.config 对我有用:

const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');

 module.exports = {
     mode: 'production',
     entry: {
         index: './index.js'
     },
     output: {
         publicPath: './out/',
         path: path.resolve(__dirname, 'out'),
         filename: '[name].js',
         chunkFilename: '[name].bundle.js'
     },
     optimization: {
         minimizer: [new TerserPlugin({
         /*chunkFilter: (chunk) => {
             // Exclude mapsjs chunk from the minification as it is already minified
             if (/mapsjs/.test(chunk.name)) return false;
             return true;
         }*/
         exclude: "mapsjs.bundle.js"
         })],
     },
     node: {
         global: false
     }
 };

推荐阅读