简体   繁体   English

评估打字稿语句时出现“ ReferenceError:模块未定义”

[英]“ReferenceError: module is not defined” when evaluating typescript statement

Here is my code 这是我的代码

// properties.ts
export const properties = {
    title: "Google"
};

// example.ts
import { properties } from './properties.ts';

console.log(properties.title); // Prints Google
console.log(eval("properties.title")); // Expected to print Google but throws ReferenceError: properties is not defined

However, console.log(eval('properties_1.properties.title')) // Prints Google 但是,console.log(eval('properties_1.properties.title'))//打印Google

But how to derive "properties_1" is my concern. 但是,如何获得“ properties_1”是我的关注。

The import statement in TS transpiles to a new variable. TS中的import语句将转换为新变量。 This is by default in typescript and eval cannot compute that. 默认情况下,这是打字稿中的内容,而eval无法对其进行计算

I tried like this and it worked, 我尝试过这种方法,但效果很好,

import { properties } from './properties';
let p = properties;
console.log(p.title); // Prints Google
console.log(eval('p.title'));

Another way you can do this by importing properties into variable, 您可以通过另一种方式将属性导入变量,

import * as properties  from './properties';
console.log(properties.properties.title); // Prints Google
console.log(eval('properties.properties.title')); // Prints Google

Make sure you compile this way, 确保以这种方式进行编译,

>tsc dynamic.ts -t ES6 -m commonjs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM