使用browersify使node.js javascript在浏览器中工作

问题描述

我已经查看了其他stackoverflow帖子,但是我似乎不太能使它正常工作。说我有如下定义的三个javascript类:

Animal.js:

class Animal {
    constructor() {
    }
    get_sound() {
        return 'animal sound'
    }
}
module.exports = Animal

Dog.js:

var Animal = require('./Animal.js')
class Dog extends Animal {
    constructor() {
        super()
    }
    get_sound() {
        return 'woof'
    }
}
module.exports = Dog

Cat.js:

var Animal = require('./Animal.js')
class Cat extends Animal {
    constructor() {
        super()
    }
    get_sound() {
        return 'meow'
    }
}
module.exports = Cat

我在node.js中加载和使用它们没有问题,例如:

...
var Animal = require('./Animal.js')
var Dog = require('./Dog.js')
var Cat = require('./Cat.js')
...
animal_type = 'Dog'
animal_class = eval(animal_type)
animal = new animal_class
sound = animal.get_sound()
console.log("sound: " + sound)
...
sound: woof

然后我运行browserify使它们在浏览器中可运行,例如:

browserify Animal.js Dog.js Cat.js -o bundle.js

但是在浏览器中,如果我使用此index.html:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="./bundle.js"></script>
    <script>
        $(document).ready(function () {
            $("#sound_button_id").click(function () {
                var animal_type = $("#animal_type_select_id").val()
                var animal_class = eval(animal_type)
                var animal = new animal_class
                var sound = animal.get_sound()
                alert("sound: " + sound)
            })
        })
    </script>
</head>
<body id="body">
    <div id="animal_div_id">
        <label>Animal Sound:</label>
        <select id="animal_type_select_id">
            <option value="Animal">Animal</option>
            <option value="Dog">Dog</option>
            <option value="Cat">Cat</option>
        </select>
        <br>
        <button id="sound_button_id" type="button">Get Sound</button>
    </div>
</body>
</html>

选择“狗”并单击按钮,出现以下错误

未捕获的ReferenceError:未定义狗

也许有人知道我的方式的错误吗?我认为关于browserify的事情我不太了解。我尝试了“ --require”选项,但出现了相同的错误

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)