首页 > 解决方案 > 通过 eval 访问模块变量时,Edge 抛出未定义的错误

问题描述

我无法在片段中模仿这一点,但使用以下代码重现:
Windows 10 || 边缘版本:42.17134.1.0 || EdgeHTML:17.17134

我正在使用ES6 模块

import * as variable_name from 'file'


console.log(variable_name); //will return an [object module]
console.log(eval("variable_name")); //returns undefined error 'variable_name is not defined'

Chrome 以这种方式工作正常。

示例 HTML

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <script type="module" src="module.js"></script>
    </body>
</html>

标签: javascriptmicrosoft-edgees6-modules

解决方案


您定义variable_name为变量值,因此您应该在不带引号的情况下使用它。也许 Chrome 中的语法规则不是那么严格,所以它可以很好地使用引号。您可以将其修改为console.log(eval(variable_name));,然后它可以在 Edge 和 Chrome 中正常工作。


推荐阅读