Unterminated string literal
By Flavio Copes
Fix the confusing JavaScript 'Unterminated string literal' error that points to no line, caused by code placed before an import, by keeping imports at the top.
The “Unterminated string literal” error means the JavaScript parser found the opening quote of a string, but never found the quote that closes it.
Most of the time the cause is easy to spot. You forgot the closing quote:
const greeting = 'hello
Or you broke a string across two lines. Regular strings can’t contain a line break:
const message = 'thanks for signing up
we will be in touch soon'
If you need a multiline string, use backticks:
const message = `thanks for signing up
we will be in touch soon`
The sneaky version: quotes inside strings
An apostrophe inside a single-quoted string can cause this too:
const status = 'it's done'
The parser closes the string at the apostrophe in it's. Then the quote at the end of the line opens a new string, which never gets closed. TypeScript reports “Unterminated string literal” right there, at the end of the line.
Escape the apostrophe with \', or switch to double quotes for that string.
When the error points nowhere
Sometimes this error is much more confusing. Sometimes I stumble on weird errors, and this was one of those days.
I hit some “Unterminated string literal” issues that didn’t point me to any line, or even a file. The editor showed no unterminated strings anywhere, which made it even stranger. If I really had a broken string, the editor would have yelled at me.
The cause of the problem was that I had some logic before an import statement.
ES module imports are meant to sit at the top of the file, and they are hoisted before anything else runs. The tooling that transforms the file expects that shape. Code interleaved before the imports tripped it up, and the error it produced had nothing to do with the real problem. No string was broken anywhere.
Removing this logic, keeping all the imports at the top, made the error go away.
So the lesson is: when a syntax error makes no sense, and your editor sees nothing wrong, stop hunting for the literal problem in the message. Look at the structure of the file instead. Imports first, everything else after.
Related posts about js: