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
Edit your
tsconfig.json
and change"module": "esnext"
to"module": "commonjs"
.This is ES type modules:
But this is commonJs type:
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 thisimport { 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
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 intoserver.js
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.