首页 > 解决方案 > 评估打字稿语句时出现“ReferenceError:未定义模块”

问题描述

这是我的代码

// 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

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

但如何推导出“properties_1”是我关心的问题。

标签: typescript

解决方案


TS 中的 import 语句转换为新变量。这是打字稿中的默认值,而eval无法计算

我试过这样,它奏效了,

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

另一种方法是通过将属性导入变量来做到这一点,

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

确保以这种方式编译,

>tsc dynamic.ts -t ES6 -m commonjs

推荐阅读