问题描述
您好,我尝试使用huejay(https://github.com/sqmk/huejay)为我的Philips Hue Lights用HTML和JS编程自己的GUI。
当我尝试在我的HTML文件中的按钮上使用来自main.js的JS函数“ LightOn()”时,出现错误: “未捕获的ReferenceError:未定义LightOn onclick文件:/// C:/Users/noName/Desktop/Hue/index.html:1“
当我使用message.js中“ Message()”的确切代码时,它将正常工作。
我将let huejay = require('huejay');
转换为import { huejay } from "huejay";
正确吗?我知道main.js中的导入huejay存在问题,但我不知道如何正确处理。我试图在代码中设置type =“ module”。
当我从终端手动运行代码时,一切正常,我的灯打开了。
请帮助...
这是我的代码:
index.html
<!DOCTYPE html>
<html lang="de">
<head>
<Meta charset="utf-8">
<title>Hue Lights</title>
</head>
<body>
<script type="module" src="main.js"></script>
<button onclick="LightOn()">Light On!</button>
<script type="text/javascript" src="message.js"></script>
<button onclick="Message()">TEST</button>
</body>
</html>
main.js
import { huejay } from "huejay";
function LightOn() {
// Client settings
let client = new huejay.Client({
host: '123.0.12.34',port: 80,// Optional
username: 'bridgeusername',// Optional
timeout: 15000,// Optional,timeout in milliseconds (15000 is the default)
});
// Test connection to the bridge
client.bridge.ping()
.then(() => {
console.log('Successful connection');
})
.catch(error => {
console.log('Could not connect');
});
// Test authentication to the bridge
client.bridge.isAuthenticated()
.then(() => {
console.log('Successful authentication');
})
.catch(error => {
console.log('Could not authenticate');
});
// Get bridge details and configuration
client.bridge.get()
.then(bridge => {
console.log(`Retrieved bridge ${bridge.name}`);
console.log(' Id:',bridge.id);
console.log(' Model Id:',bridge.modelId);
console.log(' Model Name:',bridge.model.name);
});
// Save a light's attributes and state
client.lights.getById(1)
.then(light => {
light.name = 'Living room';
light.on = 1;
light.brightness = 254;
light.hue = 32554;
light.saturation = 254;
return client.lights.save(light);
})
.then(light => {
console.log(`Updated light [${light.id}]`);
})
.catch(error => {
console.log('Something went wrong');
console.log(error.stack);
});
}
message.js
function Message() {
alert('External JS loaded');
}
解决方法
在LightOn()前面添加导出:
export function LightOn()
了解更多: https://medium.com/backticks-tildes/introduction-to-es6-modules-49956f580da