未捕获的引用错误:getChecked 未使用 Webpack Bundler 定义

问题描述 投票:0回答:1

我正在使用 Webpack 捆绑器来捆绑我的代码,但是当我在浏览器中运行 html 页面时,我收到一条错误消息,指出我的 getChecked() 函数未定义,即使 getChecked() is 已定义并包含在捆绑包中。

Uncaught ReferenceError: getChecked is not defined at HTMLButtonElement.onclick ((index):36:71)

我的项目的组织方式如下:我有一个文件“getAPIToken.js”,它通过名为 fetchToken() 的函数获取 API 令牌。我有另一个文件“fetchSymptoms.js”,它导入 fetchToken() 并使用它来获取令牌并显示一些数据。 “fetchSymptoms.js”定义了函数 getChecked(),该函数在单击按钮时执行。 “fetchSymptoms.js”是我的 webpack 捆绑器的入口点。

我不确定如何让 getChecked() 在我的浏览器中被识别。如何使 getChecked() 被我的浏览器识别?我需要先确保它已加载吗?在过去的两周里我一直在这个问题上陷入困境,所以任何帮助将不胜感激!

函数 getChecked() 在 fetchSymptoms.js 中定义如下:

 import { fetchToken } from './getAPIToken.js';
    

    fetchToken()
    .then(token => {
        fetchAdultMaleSymptoms(token);
        //fetchSymptoms(token);
    })
    .catch(error => {
        console.error('Error in fetchSymptoms ', error);
    });


function getChecked(){ //displays symptoms from checked checkboxes
    //alert("hello!");
    const checkboxes = document.getElementsByName("symptom"); //items contains nodelist with the checked symptoms
    const array=[]; //create empty array

    for (var i = 0; i < checkboxes.length; i++){ //run through the nodelist
        if (checkboxes[i].type == "checkbox" && checkboxes[i].checked == true){
            if (!array.includes(checkboxes[i].value)){ //if the symptom is not already in array, then push
                array.push(checkboxes[i].value); //add checked items to array
            }
        }
    }

    const jsonArray = JSON.stringify(array); //converts to json string
    sessionStorage.setItem("checked", jsonArray); //will disappear when browser window closed, can use localStorage
}

因此函数被定义,然后最终被捆绑,因为 fetchSymptoms.js 是入口点。以下是我在index.html 中使用getChecked() 的方法。当在我的浏览器中运行时,index.html 给出错误,指出未捕获的 getChecked() 未定义。


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/css/index.css" rel="stylesheet">
    <title>Prognosis Pal</title>
   
    <script src="bundle.js"></script>
    <script src="/js/fetchSymptoms.js"></script>

    <script src="/js/displayCategories.js"></script>
    <!-- <script src="/js/diagnosisSymptoms.js"></script> -->
    
</head>

<body>
    <a href="/you"><button class="you-button">You</button></a>

    <h1>PrognosisPal</h1>

    <div>Select all symptoms that apply</div>

    <div class="symptoms-container">
        <form action="#" id="symptomForm">  
            <div id="ul-container"></div>
            <!-- Symptoms used come from API -->
        
        </form>
    </div>

    <!-- getChecked() gets the values that the user selects for symptom checkboxes-->
    <a href="/diagnosis"><button type="submit" onclick="getChecked()">Diagnosis Me!</button></a>
</body>
</html>

最后,这是我的 webpack.config 文件:

const path = require('path');
//require('dotenv').config({ path: './functions/.env' }); 
const Dotenv = require('dotenv-webpack');


module.exports = {
  entry: './public/js/fetchSymptoms.js', //entry point of your application ./public/js/getAPIToken.js
  output: {
    filename: 'bundle.js', //output bundle filename, where result is going to go
    path: path.resolve('public'), //output directory
  },
  mode: 'none',
  module: {
    rules: [
      {
        test: /\.js$/, // Match JavaScript files
        exclude: /node_modules/, // Exclude node_modules
        use: {
          loader: 'babel-loader', // Use Babel to transpile JavaScript
          options: {
            presets: ['@babel/preset-env'] // Use the preset for modern JavaScript
          }
        }
      }
    ]
  },
  plugins: [
    new Dotenv(),
  ],
  resolve: {
    extensions: ['.js'],
    alias: {
      'crypto-js': path.resolve(__dirname, 'node_modules/crypto-js'),
    },
  },
};

我不确定如何让 getChecked() 在我的浏览器中被识别。我的 webpack.config 文件中是否需要某种 html 插件?在过去的两周里我一直在这个问题上陷入困境,所以任何帮助将不胜感激!

javascript webpack uncaught-reference-error
1个回答
0
投票

这个问题与此类似,可以查看这里的解决方案链接

我就总结一下吧

当您通过 webpack 运行文件时,webpack 会尝试不乱扔全局范围,因此该函数将不可用 默认全局。

如果你希望该函数可以在 JS 范围之外访问 文件,你应该把它放在全局范围内。

function uclicked() {
  // do something
}
window.uclicked = uclicked;

或者只是:

window.uclicked = function() {
  // do something
}
© www.soinside.com 2019 - 2024. All rights reserved.