0

It seems as if the webpack-dev-server overwrites (or resets perhaps?) the native JSON-object back to the original on every recompile.

I'm using a library called defiant.js. It extends the global JSON object with an extra function JSON.search(). The specific code looks like this:

if (!JSON.search) {
    JSON.search = function(tree, xpath, single) {
       ... <snip> ...
    };
}
console.log(JSON); // JSON now has parse, stringify and search (and more).

This works nice when building using webpack, but when running with webpack-dev-server it will cause JSON to be overridden almost immediately (seemingly on WDS compile?).

I test this by typing JSON into the console, which gives output:JSON {Symbol(Symbol.toStringTag): "JSON", parse: function, stringify: function} which is the same as before defiant has loaded.

I have both tried to include the file directly in my index.html:

<script type="text/javascript" src="defiant.min.js"></script>

And by packing it in (sorry, verbose):

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const express = require('express');
let dist = 'dev';
let APP_DIR =  path.resolve(__dirname);
console.log(APP_DIR);
module.exports = {
  context : APP_DIR,
  entry : {
    pc2sp : './index.js',
    vendor:['defiant.js/dist/defiant.js']
  },
  output : {
    path : __dirname + '/dist/' + dist,
    publicPath : '',
    filename : '[name].[hash].js',
  },
  devtool : 'source-map',
  externals : { },
  resolve : { modules : [ 'node_modules' ] },
  module : {
    rules : [
      {
        enforce : 'pre',
        test : /\.js$/,
        exclude : /node_modules/,
        loader : 'jshint-loader'
      },
      {
        test : /\.html$/,
        use : [ {loader : 'html-loader', options : {minimize : false}} ]
      }
    ]
  },
  plugins:[
    new HtmlWebpackPlugin({
      template : APP_DIR + '/index.html',
      chunks : [ 'pc2sp', 'vendor' ],
      alwaysWriteToDisk : true
    }),
  ],

  devServer : {
    host : 'localhost',
    open : true
  }
};

But to no avail. Also using or not using flags like --hot or --inline or --lazy makes no noticeable difference. So, How can I prevent webpack-dev-server from replacing the global JSON-object?

Example using images:

Using webpack (or plain html/js):

webpack

Using webpack-dev-server

webpack-dev-server

Any hints or ideas are most welcome!

ippi
  • 9,857
  • 2
  • 39
  • 50
  • 1
    Related: https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice – Caramiriel Jun 23 '17 at 07:07
  • Yes, fair point. I don't deny extending default objects can be bad, or even argue that it isn't bad in this specific case. Heck, it's not even my code. All I want is to do is prevent webpack-dev-server from overriding or resetting it to default. Maybe there is a way to hook a function to run when webpack-dev-server recompiles? – ippi Jun 23 '17 at 07:15

0 Answers0