rareyesdev / react-template

[⛔️ DEPRECATED] Template for React projects
0 stars 0 forks source link

Use NPM debug package #34

Open rareyesdev opened 6 years ago

rareyesdev commented 6 years ago

It seems a good idea to have some debug statements that log application state. This code will be removed in production using strip-loader and webpack.NormalModuleReplacementPlugin

Webpack configuration that will remove debug code in production:

const path = require('path');
const webpack = require('webpack');
const webpackStrip = require('strip-loader');

const nodeEnv = process.env.NODE_ENV;
const mode = nodeEnv;
const removeDebugCalls = nodeEnv === 'production';

const plugins = [
  new webpack.EnvironmentPlugin(['NODE_ENV']),
];
removeDebugCalls && plugins.push(new webpack.NormalModuleReplacementPlugin(/debug/, path.resolve(__dirname, 'src', 'noop-debug.js')));

const rules = [
];
removeDebugCalls && rules.push({
  test: /\.js$/,
  loader: webpackStrip.loader('debug', 'debugFactory', 'debugFactory.enable', 'debugFactory.disable', 'console.log')
});

module.exports = {
  mode,
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules
  },
  plugins
};

Example of usage in file:

import debugFactory from 'debug';

if (process.env.NODE_ENV === 'development') {
  console.log('enabling logging');
  debugFactory.enable('*');
} else {
  debugFactory.disable();
}

var debug = debugFactory('d1name');

debug('d1message');