skip to Main Content

So I’m trying to implement typescript to an existing project.

However, I came to a stop, where I get an error of: SyntaxError: Cannot use import statement outside a module

Here, is my helper class, which is omitted. However, you can see that I am using an import, rather than require

index.ts

// const axios = require('axios');
// const {includes, findIndex} = require('lodash');
// const fs = require('fs');
import { includes, findIndex } from "lodash";
import fs from 'fs';

type storeType = {
  [key: string]: string | boolean
}

class CMS {
  _store;

  constructor(store: storeType) {
    this._store = store;

<omitted code>


export default CMS;
  }

Than, I import index.ts file to server.js file:

const { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } = require('./src/utils/cms/index.ts');

Unfortunately, when I start the server, I get an error of: SyntaxError: Cannot use import statement outside a module

I am using a default tsconfig.json which has been generated after creating file and running dev environment.

3

Answers


  1. Edit your tsconfig.json and change "module": "esnext" to "module": "commonjs".

    Login or Signup to reply.
  2. This is ES type modules:

    import { includes, findIndex } from "lodash";
    import fs from 'fs';
    

    But this is commonJs type:

    const { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } = 
    require('./src/utils/cms/index.ts');
    

    I think that’s the problem. You should use one type of modules.
    Try to rewrite this const { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } = require('./src/utils/cms/index.ts'); to this import { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } from './src/utils/cms/index.ts'

    Or opposite rewrite ES to commonJs, but don’t forget to change type in tsconfig

    Login or Signup to reply.
  3. You cannot explicitly import typescript files into Javascript files. Instead, you need to use the compiled typescript files(i.e. Javascript files in outDir folder).

    So assume you compiled your typescript files into Javascript, then it would be converted to outDir/index.js. After that, you could directly import it into server.js

    const { CMS, getCookie, checkLang, getLangByDomain, handleRoutes } = 
      require('./path/to/index.js'); // You cannot require a ts file.
    

    If the typescript files and Javascript files are part of the same project, then you need to transpile the js files alongside the ts as well. In order to achieve this, you need to set allowJs to true in tsconfig.

    { 
      "compilerOptions": {
       ...
       "allowJs": true,
      }
    }
    

    Allow JavaScript files to be a part of your program. Use the ‘checkJS’ option to get errors from these files.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search