If you are learning Vue.js, and you are trying to solve a specific problem, you might already ran into StackOverflow examples where you see that console.log is being used to display a data. However, after you’ve tried to implement it, you got an error:
If you are desperately trying to understand what you had typed wrong and why Vue js console log is not working, calm down. Console log can be used in Vue js application, however it is disabled.
The reason for this, is that it is not a good practice to use methods on console. But, if you want to test something, for example if a method gets the data, by default, you can’t use console log to check this. Yet, using console log is a common practice used by the developers (doesn’t mean this practice is perfect).
However, if you find the feature of console handy during the development (well yeah, it is handy), you can always enable it. Just be cautious and don’t forget to disable it when shipping your app to the world. What would be worse is delivering your application with a console log statement left in the code.
TIP: If you don’t need console log specifically, you can remove the burden of configuration and use the window.console.log() instead.
How to fix the error and enable console log for Vue js?
First, let’s talk why console log can’t be used in Vue js applications by default. The reason for this is Eslint. If you are not familiar with Eslint, don’t spin your head about it. All you need to know that it is a static code analysis tool for identifying problematic patterns.
So Eslint disables the console function by default for the lifecycle components. Good news is that it is just a matter of configuration and it can be enabled easily.
If you had created Vue project with CLI, you have Eslint as one of the dependencies. The only step that has to be implemented is to change the configurations of Eslint in the file that might sound familiar to you – it’s package.json.
You can solve this problem easily by adding an additional line of configurations in the package.json file. Open the file and search for the eslintConfig. The json part should look like this:
Pay attention to the line that starts with “rules”. This is where all the magic will happen. Inside the curly braces of the “rules”, insert a new role – a one that will let you to use the console log function:
Now save the file and reload the “npm run serve” in order your changes to take effect. Now you should able to use console log with Vue.js!
A simple way how can you benefit from console function
If you will be reusing the console log in different components, no need to rewrite the whole statement every time. You can declare an instance property in the main.js file and name it “log” (or give it even one-letter name), in this way the statement becomes shorter. Might not be a significant improvement, but if you are obsesed with making your app perfect – it is one of the mini upgrades.