Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable ECMAScript "use strict" globally?

I have a project with literally hundreds of JavaScript source files. I am wondering what is the best way to enable the strict mode for the project? I understand the consequences of this action and I am only looking for advice regarding the deployement of this feature. Placing "use strict" in every file does not seem fun.

like image 481
Tower Avatar asked Jan 22 '11 17:01

Tower


People also ask

How do you enable strict mode in JavaScript?

Declaring Strict Mode Strict mode is declared by adding "use strict"; to the beginning of a script or a function.

Is ES6 strict mode by default?

ES6 modules and classes are strict by default.

Which command will run script js with strict mode?

Strict mode for scripts To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict'; ) before any other statements.

Should I use use strict in ES6?

In ES5, the Strict Mode is optional but in ES6, it's needed for many ES6 features. So most people and tools like babel automatically add “use strict” at the top of the file putting the whole JS code in strict mode and forcing us to write better JavaScript.


2 Answers

Well, I'm not clear on the context your javascript files will be used in, however say the context is a dynamic web application where various page files, javascript files, style sheets, etc, etc, are loaded when needed, then I would just create a single javascript file with only "use strict" within it. Then, include that file in your head tags, preceding all other javascript files and make sure that if you will be inserting javascript files dynamically into the head of the document of a given web application that you append them after your "use strict" .js file.

That way you won't have to go through each of your .js files and modify them individually.

like image 160
Xaxis Avatar answered Sep 25 '22 21:09

Xaxis


As I see there is no possibility to enable "use strict"; globally. I had similar problem with it, and I were forced to write script to do it easily and quick (I had more that 200 files in project), some of files already contained that statement, some not, so I checked it before adding. Here I attach my solution written as bash command.

for path in path1 parh2 anotherPatr; do for file in $(find $path -name "*.js"); do if [[ $(grep "use strict" $file | wc -l) -gt 0 ]]; then echo $file "already use strict"; else sed -i '1i\"use strict\";' $file; fi; done; done;

Sorry, that looks so ugly but I did not write this in script file I just execute it in the command line.

like image 25
bladekp Avatar answered Sep 21 '22 21:09

bladekp