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.
-
9Placing "use strict" in every file seems like a scriptable task. – Jan 22 '11 at 17:51
-
I guess I could try macros in my IDE for this one. Now I would have a reason to learn them... – Tower Jan 22 '11 at 17:54
-
@delnan, Well it's better if it doesn't need to be done that way. – Pacerier Apr 20 '16 at 16:17
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.

- 10,632
- 9
- 60
- 68

- 1,935
- 15
- 17
-
1My understanding is that "use strict" only applies to the file it is in, so what you suggest wouldn't work. – Darshan Rivka Whittle Jun 17 '12 at 05:44
-
Please reread what I said. The "use script" is placed in its own .js file which when included in a given file will have effect on the file it is being included in as well as all other .js files that are included in the page. It does work, I've been using this method for a year or so. – Xaxis Sep 17 '12 at 22:27
-
8I'm not sure why this answer is accepted or upvoted. Xaxis' comment is different from what is written in the answer (maybe it was changed in editing). @Darshan is correct. 'use strict' is scoped to the function or the file. Including a – Malcolm Dwyer Mar 06 '14 at 16:17
-
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.

- 1,529
- 22
- 29