【问题标题】:debugging JavaScript with Webpack使用 Webpack 调试 JavaScript
【发布时间】:2021-09-13 11:09:29
【问题描述】:

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

错误: 未捕获的 ReferenceError:未定义画布 在: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'
        })
    ],
}

【问题讨论】:

    标签: javascript google-chrome debugging webpack


    【解决方案1】:

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

    如果您的意思是仅在开发时访问,最简单的方法是手动公开您想要访问的内容:

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

    那么你应该能够从控制台与之交互。

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

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 2017-09-23
      相关资源
      最近更新 更多