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"
],