Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  35] [ 3]  / answers: 1 / hits: 18104  / 4 Years ago, wed, march 11, 2020, 12:00:00

I want to have console logging while I'm developing in Vue.js but want it disabled for production.


There is a module vuejs-logger that works fine inside of a Vue component and will be disabled in production mode. But it will not work (for instance) in my service files or library files (outside of the Vue instance) nor in Vuex.


Does anyone have any other suggestions? Vue.js integrated or otherwise?


Stay safe, TIA


Edit: Just to clarify, vuejs-logger's Typescript integration is the real problem. It throws up so many TS errors that I cannot use it. The actual JS logging seems to work... I'm still interested in other solutions that may work smoothly.


More From » typescript

 Answers
12

Consider building your own simple wrapper which will work everywhere, assuming you are using Webpack, like the following:


declare const NODE_ENV: any;

export function log(message: String, level?: 'info' | 'warn' | 'error') {

// WHEN RUNNING WEBPACK WITH `PRODUCTION` build,
// IT WILL REMOVE THE FOLLOWING CODE.

if (NODE_ENV !== 'production') {

if (level === 'error') {
console.error(message);
} else if (level === 'warn') {
console.warn(message);
} else {
console.log(message);
}
}
}

Being a simple function, you can literally import this anywhere in your code including component files or other non-component files. The important point here is to note the use of the NODE_ENV variable which will be injected by Webpack when running in Production mode. Similar setups exist for Rollup and other bundlers. Read more about this here. When Webpack is bundling the code with production mode, it will ignore the code inside if (NODE_ENV !== 'production') { /* some code */ } construct.


Also, if you need to wrap it inside a plugin so that it is available on every component instance using the this pointer then:


const MyLogger = {
install(Vue: Vue, options: any) {

// Add an instance method
Vue.prototype.log = log;
}
};

Vue.install(MyLogger);

Of course, if you are using TypeScript, then you must teach TypeScript using module augmentation like this:


import Vue from 'vue';

declare module 'vue/types/vue' {
interface Vue {
log(message: string, level?: 'info' | 'warn' | 'error'): void;
}
}

The above snippet should be present inside your typings folder like specified using tsconfig.json. The directory path would be: ROOT/typings/vue/index.d.ts.


In tsconfig.json file, typings array should be set to:


"typeRoots": [
"./node_modules/@types",
"./typings"
],

[#51142] Thursday, February 27, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;