首页 > 解决方案 > HTML 元素无法访问 JS 功能。未捕获的 ReferenceError:未定义 X。网页包

问题描述

我正在使用具有以下配置(webpack.config.js)的 webpack:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  plugins: [
    new CleanWebpackPlugin(),
    new ManifestPlugin(),
    new CopyPlugin([
      { from: './src/models', to: './models' },
    ]),
    new HtmlWebpackPlugin({
      template: './src/index.html',
      // chunks: ['vendors', 'polyfills', 'main', 'global'],
      // chunksSortMode: 'manual',
      inject: 'body'
    }),
  ],
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
    // contentBase: './src'
  },
  mode: "development",
  output: {
    filename: 'dist/my-index.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader',
        ],
      },
    ],
  },
};

我的 Index.html 如下:

<!doctype html>
<html>
  <head>
    <title>Getting Started with webpack</title>
<!--    <script src="my-index.js" async defer></script>-->
    <script type="text/javascript" async src="dist/my-index.js"></script>
  </head>
  <body>
    <div style="position: relative" class="margin">
      <video onplay="onPlay(this)" id="inputVideo" autoplay muted></video>
      <canvas id="overlay"/>
    </div>
  </body>
</html>

我的 index.js 包含以下重要部分:

import _ from 'lodash';

document.addEventListener("DOMContentLoaded", function(event) {
  //do work
  console.log('Document loaded');

  Promise.all([
  ...
  ]).then(run)

});

function onPlay(element) {
  console.log('OnPlay has been called with element ', element);
}

async function run() {
  console.log('3. Running...');

  const videoEl = document.getElementById('inputVideo')
  navigator.getUserMedia(
      { video: {} },
      stream => videoEl.srcObject = stream,
      err => console.error(err)
  )
}

当我运行时npm run start,它基本上执行了这个脚本: "start": "webpack-dev-server --open",

浏览器的控制台打印:

Document loaded
3. Running...

然后是一个错误

(index):10 Uncaught ReferenceError: onPlay is not defined
    at HTMLVideoElement.onplay ((index):10)

看起来 onPlay 不在同一范围内。如果我像这样将 onPlay 函数直接插入 index.html

<head>
  <script>
    function onPlay(element) {
      console.log('OnPlay has been called with element ', element);
    }
  </script>
</head>

那么这将起作用并找到JS函数。但显然这不是我需要的。看起来我错误地配置了 HtmlWebpackPlugin。

任何帮助将非常感激。

标签: javascriptwebpackwebpack-dev-serverhtml-webpack-plugin

解决方案


推荐阅读