Search code examples
javascriptvisual-studio-codeprettier

On saving, Prettier formats "use strict"; to ('use strict'); & strict mode is not initialised?


I'm pretty new to coding & using VS Code / Prettier I'm trying to turn on strict mode in my JS code, using "use strict";

when I save my file, Prettier formats the code from "use strict" to ('use strict');

which then as far as I can see means strict mode isn't initialised. I couldn't find anyone else talking about this problem online anywhere, so wonder if anyone could shed any light on it?


Solution

  • Assuming you have tried with a recent version of Prettier, this indicates you have put "use strict"; at a wrong place.

    "use strict"; must appear before any code in the script, or when it is used within a function, it must appear before any code in the body of that function.

    If you put "use strict"; anywhere else, Prettier will add the parentheses.

    You can reproduce this behaviour on the Prettier playground.

    which then as far as I can see means strict mode isn't initialised

    True. It must be a plain string literal, and ("use strict") violates that rule.