Typescript SyntaxError: Cannot use import statement outside a module (side file containing functions)

Issue

I am creating a minecraft bot using mineflayer library. After a bit of work I decided to make code readable and reusable (image of file organisation) and also start using typescript. I have read a lot of stack threads and other articles as this problem is quite popular. However, after trying all of it the problem still persists.

Edit, important change:

I have tried compiling it with tsc bot.ts --resolveJsonModule and then node bot.js. It turns out it works just fine, so now the problem narrows down to configuring WebStorm running options.

Here is what I have already done

  • package.json "type": "module -> TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for path
  • tsconfig.json has "esModuleInterop": true
  • use const util = require('./utils/util') and use util.function() -> same error as in 1st step

Running whole code

As I am using WebStorm, this is what I have in running options: image (just to clarify that I don’t run code from terminal)

Recreating problem in simplified environment

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"
  }
}

Related threads

import { parse } from 'node-html-parser';
parse = require('node-html-parser');

but the IDE gives me TS2632: Cannot assign to 'util' because it is an import. error.

Solution

Fixed by changing:

import {util} from "./utils/util"

To:

const util = require('./utils/util')
// or
const { sleep, random, eatAny, clickItem, lookAtEntity} = require('./utils/util')

Afterall I don’t know why compiling with tsc had been working well while webstorm was throwing out error. I just changed the import ES6 syntax to require() CommonJS.

Answered By – jancor

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.