javascript - 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。
任何帮助将非常感激。
解决方案
推荐阅读
- c# - ExcelReader 工厂在最后一个写入行失败
- javascript - 六边形网格算法失败
- python-3.x - 有什么方法可以按日期对 apache 日志进行排序?
- angular - 我的 Angular 应用程序的容器无法与 Docker 上的 API 容器通信
- javascript - 页面完全加载后,嵌入式 Outlook 365 日历会自动滚动到日历部分
- asp.net-core - mvc 参数开头的斜线
- selenium - 如何在 chrome devtools 命令行中交互式执行 selenium-webdriver / protractor 命令?
- php - 无法解析的依赖解析 [参数#0 [
$app ]] 在 Illuminate\Support\Manager 类中 - node.js - Mongoose:将 $skip 和 $limit 之后的所有字段数相加
- swift - 如何为按钮设置动画以超出视图范围