使用 Webpack 调试 JavaScript

debugging JavaScript with Webpack

当我在 chrome 中打开控制台时,会显示该对象。但是为什么我不能访问它?

错误: 未捕获的 ReferenceError:canvas 未定义 在 :1:1

main.js

import { Canvas } from "./models/canvas.class.js";

const cvs = document.getElementById('cvs');
const ctx = cvs.getContext('2d');

let canvas = new Canvas(ctx);

function loop() {
    canvas.getLog();
    requestAnimationFrame(loop);
}
loop();

canvas.class.js

export class Canvas {

    ctx;

    constructor(ctx) {
        this.ctx = ctx; 
    }

    getLog() {
        console.log(this);
    }

}

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: './src/js/main.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        clean: true
    },
    mode: 'development',
    plugins: [
        new HtmlWebpackPlugin({
            inject: false,
            template: './src/index.html'
        })
    ],
}

简而言之,您的代码按预期工作;但是您缺少来自控制台的开发测试访问权限?这是 webpack 的一个特性——它隔离了每个模块,所以没有任何东西落在全局范围内。

如果您指的只是开发时访问,最简单的方法就是公开您想要手动访问的内容:

let canvas = new Canvas(ctx);
window.canvas = canvas;

那么您应该可以从控制台与其进行交互。

或者,您可以在代码中放置一些断点,然后在调试器中访问它。