我正在使用 mineflayer 创建一个我的世界机器人图书馆。经过一些工作后,我决定使代码可读和可重用(image of file organisation)并开始使用 typescript 。我已经阅读了很多堆栈线程和其他文章,因为这个问题很流行。然而,在尝试了所有这些之后,问题仍然存在。
编辑,重要变化:
我试过用 tsc bot.ts --resolveJsonModule
编译它然后 node bot.js
.事实证明它工作得很好,所以现在问题缩小到配置 WebStorm运行选项。
这是我已经完成的
- package.json
"type": "module
->TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for
路径 - tsconfig.json 有
"esModuleInterop": true
- 使用
const util = require('./utils/util')
并使用util.function()
-> 与第一步中的错误相同
运行整个代码
当我使用 WebStorm 时,这是我在运行选项中的内容:image (只是为了澄清我不从终端运行代码)
在简化环境中重现问题
bot.ts
import {util} from "./utils/util" // error is thrown right away, so other lines are irrelevant I guess
const mineflayer = require('mineflayer')
const bot = mineflayer.createBot()
util.ts
import * as config from "../config/config_main.json"
export module util {
export function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
export function random(list) {
if (list[0] === list[1]) return list[0];
return Math.floor(Math.random() * (list[1] - list[0])) + list[0];
}
}
config_main.json
{
"bot": {
"username": "username",
"password": "password"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": false,
"skipLibCheck": true
}
}
package.json
{
"type": "module",
"name": "mcbot",
"main": "bot.js",
"scripts": {
"test": "None"
}
}
相关话题
- SyntaxError: Cannot use import statement outside a module -
"type": "module"
不能像更改扩展名一样工作.mjs
不可行,因为我使用的是 typescript - "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 - 从这里开始尝试
import { parse } from 'node-html-parser';
parse = require('node-html-parser');
但是 IDE 给了我 TS2632: Cannot assign to 'util' because it is an import.
错误。
最佳答案
首先,从 package.json 中删除 type:module
。然后从 tsconfig.json 中删除 module:commonjs
。使用 export default function util () {}
语法。如果您已完成前两个步骤,命名导出也将适用于本地文件。
原因
您正在混合使用 es6 和 commonjs。 module:commonjs
将其强制为 commonjs 而 esModuleInterop
将其强制为 es6。并且 type:module
显示 es6 错误并强制写入文件扩展名,首先将其删除
警告
命名导入不适用于 npm 包。就像你不能使用一样
从“some-package”导入{something};
相反,导入默认的,然后访问命名的。
从“some-package”导入 defaultExport;
const something = defaultExport.something
关于javascript - typescript 语法错误 : Cannot use import statement outside a module (side file containing functions),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71929951/