javascript 使用Webpack、Babel和Terser进行打包和缩小时未捕获的构造函数错误

2nc8po8w  于 2023-10-14  发布在  Java
关注(0)|答案(2)|浏览(82)

我正在尝试使用简单的JavaScript创建一个websdk。当我使用Webpack、Babel和Terser进行缩小和捆绑时,它会生成一个Webpack. js文件,但当我在HTML中使用它时,它会在HTML页面加载时给我一个错误。

我尝试过改变和使用不同的软件包,但问题仍然存在。为了重现这个问题,我在这里给出了一些代码片段。希望有Maven指导我解决这个问题。

// SDKContract.js
class SDKContract {
    constructor() {}

    getLocation(callback) {
        throw new Error("getLocation method not implemented");
    }
}

// GeolocationAdapter.js
class GeolocationAdapter extends SDKContract {
    getLocation(callback) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                const location = {
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude
                };
                callback(location);
            }, function (error) {
                callback({
                    error: "Location access denied or unavailable."
                });
            });
        } else {
            callback({
                error: "Geolocation not supported by this browser."
            });
        }
    }
}

// LocationWrapper.js
class LocationWrapper extends SDKContract {
    constructor(adapter) {
        super();
        this.adapter = adapter;
    }

    getLocation(callback) {
        this.adapter.getLocation(callback);
    }
}

//main.js

import GeolocationAdapter from './src/GeolocationAdapter';
import LocationWrapper from './src/LocationWrapper';

// Your application code using the SDK components
const geolocationAdapter = new GeolocationAdapter();
const locationWrapper = new LocationWrapper(geolocationAdapter);

document.getElementById("getLocationButton").addEventListener("click", function () {
    locationWrapper.getLocation(function (location) {
        if (location.error) {
            document.getElementById("locationResult").innerText = "Error: " + location.error;
        } else {
            document.getElementById("locationResult").innerText = "User Location: " + location.latitude + ", " + location.longitude;
        }
    });
});

这是我的HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Location Capture Example</title>
</head>
<body>
  <h1>Location Capture Example</h1>
  <button id="getLocationButton">Get User Location</button>
  <div id="locationResult"></div>
  <script src="./dist/bundle.js"></script>
</body>
</html>

Webpack配置

// webpack.config.js
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
    ],
  },
  optimization: {
    minimizer: [new TerserPlugin()],
  },
};

Package.json

{
  "name": "jssdk",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.23.0",
    "@babel/preset-env": "^7.23.2",
    "babel-loader": "^9.1.3",
    "terser-webpack-plugin": "^5.3.9",
    "webpack": "^5.88.2",
    "webpack-cli": "^5.1.4"
  }
}

我在webpack devtool: 'source-map'中包含了source-map。从配置中删除优化部分

optimization: {
    minimizer: [new TerserPlugin()],
  },

这样,它就指向了这一行错误:const geolocationAdapter = new GeolocationAdapter();我不明白这有什么不对。-

ogq8wdun

ogq8wdun1#

我怀疑错误消息中的t()getLocation()的缩小/编译名称。看起来它在扩展类中寻找调用super()的构造函数。相反,它会找到方法,然后抛出错误,指出该方法不是构造函数。
我认为你必须添加调用super的构造函数。JS中的扩展类总是必须调用super()函数,即使你没有传递任何属性:

constructor() {
    super()
}

看起来你在LocationWrapper中调用了它,但在GeolocationAdapter中没有。所以:

class GeolocationAdapter extends SDKContract {
    
    // Have to call super()
    constructor() {
        super()
    }

    getLocation(callback) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                const location = {
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude
                };
                callback(location);
            }, function (error) {
                callback({
                    error: "Location access denied or unavailable."
                });
            });
        } else {
            callback({
                error: "Geolocation not supported by this browser."
            });
        }
    }
}
wqnecbli

wqnecbli2#

首先,您需要确认该脚本是否适用于原始源代码。第二,确保正确调用入口点。

相关问题