所以代码很简单:

电话.json

{"SERVER":{
    "requests":{
      "one":"1"
    }
} }

文件ts

import json = require('../static/电话.json');
console.log(json.SERVER);

生成的javascript是正确的,在运行node js服务器时,控制台会记录json.服务器应打印"{requests:{one:'1'}}".

The typescript compiler (commonjs) however, somehow does not particularly like this situation and throws: "Cannot find module '../static/电话.json'".

当然,我试着写了一封信.d、 ts文件,如下所示:

declare module '../static/电话.json'{
    var exp:any;
    export = exp;
}

这显然会抛出:"环境模块声明不能指定相对模块名".

我还try 了不同的变体,比如:

declare module '电话.json' {
    import * as json from '/private/static/电话.json';
    export = json;
}

然后要求:

import json = require('电话.json');

没有一个能正常工作,并且有自己的小编译器错误:)

我想用外置的.json文件,因为我使用commonjs serverside和amd clientside,我想要一个文件来加载常量.

推荐答案

使用var而不是import.

var json = require('./calls.json');

你加载的是一个JSON文件,而不是一个模块,所以在这种情况下不应该使用import.当使用var时,require()再次被视为正常函数.

如果您使用的是 node .js定义,一切都应该正常,否则需要定义require.

Node.js相关问答推荐

即使DDB键不存在, node Lambda也不会失败,并返回NULL作为结果

Sveltekit停靠的应用程序找不到从Build导入的包

Webpack:如何避免导出函数的重命名?

FHIR 服务器:尽管 JSON 格式正确,但在 POST 请求中接收未定义请求正文

try 使用 pdf.js 时 pdf.getPage 不是函数

Node fetch 实现似乎与 Deno 和 Bun 不同,导致网站没有返回响应?

使用NodeJS通过服务账号列出Google Workspace用户

2023年如何在Node.js中使用Gmail发送邮箱?

错误 node :错误:绑定消息提供 16 个参数,但准备语句需要 15 个

为什么我的 npm 脚本中的 glob 不起作用?

如何在没有云功能的情况下使用 Google PubSub

如何调用同名的两个函数?

将已保存的卡片从条带显示到前端

Sharp JS 依赖关系 destruct 了 Elastic Beanstalk 上的 Express Server

如何为一个网站实现这 2 个网址.即 www.administrator.sitename.com 和 www.sitename.com?

如何申请在NextJS上下载文件的许可?

如何使用 Node.js 将 base64 编码图像(字符串)直接上传到 Google Cloud Storage 存储桶?

如何在 MongoDB 中查询引用的对象?

node.js 中存储的模块变量在什么范围内?

如何调试 Gulp 任务?