Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script created by webpack executing twice

I have a script which makes an ajax call to get data through an api. Below is the script (in typescript). I use webpack and babel-loader to first compile typescript (.tsx) to javascript (.jsx), which then gets transpiled to es2015 by babel into (.js)

I am using the script so generated in an html page. When looked through chrome console it shows two ajax request being passed consecutively, though only one is there. Even when I remove the ajax call, any react dependency etc, I still can see the script running twice and hitting the breakpoint twice.

In call stack, I can see webpack calling the script both the times. I am not getting why the script is being rendered twice. Please help.

Script which is getting rendered twice: (PropertyDashBoard.tsx)

import * as React from 'react';
import * as DOM from 'react-dom';
import PropertyDisplay from './Components/PropertyDisplay';

var $ = require('jquery');

// Insert the div id where the main component has to be attached
const divToAttach = document.getElementById('property-list');

const Url: string = "/api/GetProperty";

$.ajax({
    url: Url,
    dataType: 'json',
    success: (data) => DOM.render(<Main toDisplay={data}/>, divToAttach),
    error: () => console.log("Some Error occurred while getting property data")
});

class Main extends React.Component<any, any>
{
    constructor(props: any)
    {
        super(props);
    }

    public render()
    {
        var rows = [];
        this.props.toDisplay.map((val, key) => rows.push(<PropertyDisplay obj={val} key={key} />));
        return (
            <div className="property-container">
                {rows}
            </div>
                );
    }

}

tsconfig.json :

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./wwwroot/node/js",
    "jsx": "preserve",
    "module": "es6",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "outDir": "Tsbuild",
    "sourceMap": true,
    "target": "es6"
  },
  "exclude": [
    "node_modules"
  ]
}

webpack.config.js :

/// <binding />
var webpack = require('webpack'),
    path = require('path'),
    WebpackNotifierPlugin = require('webpack-notifier');
    //CompressionPlugin = require("compression-webpack-plugin");


module.exports = {
    devtool: 'eval',
    debug: true,
    entry: {
        'PropertyDashBoard': './Views/ManageProperty/Scripts/PropertyDashBoard.tsx',
        'EditProperty': './Views/ManageProperty/Scripts/EditProperty.tsx',
        'vendor':['react','react-dom','jquery','redux','bootstrap']
    },
    output: {
        path: './wwwroot/js',
        filename: '[name].js'
    },
    watch: true,
    resolve: {
        // Look for modules in .ts(x) files first, then .js(x)
        extensions: ['', '.ts', '.tsx', '.js', '.jsx','.css'],
        // Add 'src' to our modulesDirectories, as all our app code will live in there, so Webpack should look in there for modules
        modulesDirectories: ['src', 'node_modules'],
    },
    module: {
        loaders: [
            { test: /\.jsx?$/,exclude: /node_modules/ ,loaders: ['babel-loader'] },
            { test: /\.tsx?$/,exclude: /node_modules/ , loaders: ['babel-loader', 'ts-loader']},
            { test: /\.css$/, exclude: /node_modules/ ,loader: "style!css" }
        ]
    },

    stats: {
        colors: true,
        modules: true,
        reasons: true,
        errorDetails: true
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        }),

         new WebpackNotifierPlugin({ alwaysNotify: true }),
         new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),

    ],
};

I have seen for multiple inclusion of this script in entire solution but there is only one inclusion in the html where it has to be.

For backend I am using ASP.NET Core 1.0, just in case if it matters to this question.

[Edit]: These are the stats generated by webpack:

C:\Users\HP\documents\visual studio 2015\Projects\ThePropertyCore\src\ThePropertyCore> cmd /c SET NODE_ENV=development&& webpack -d --color
ts-loader: Using [email protected] and C:\Users\HP\documents\visual studio 2015\Projects\ThePropertyCore\src\ThePropertyCore\tsconfig.json
Hash: e3d28f770251608fe338
Version: webpack 1.14.0
Time: 7748ms
                   Asset     Size  Chunks             Chunk Names
         EditProperty.js     2 kB       0  [emitted]  EditProperty
    PropertyDashBoard.js  34.1 kB       1  [emitted]  PropertyDashBoard
        vendor.bundle.js  1.17 MB       2  [emitted]  vendor
     EditProperty.js.map  2.62 kB       0  [emitted]  EditProperty
PropertyDashBoard.js.map  27.9 kB       1  [emitted]  PropertyDashBoard
    vendor.bundle.js.map  1.34 MB       2  [emitted]  vendor
   [0] multi vendor 76 bytes {2} [built]
    + 210 hidden modules
Hash: af289267d69e627d7f57
Version: webpack 1.14.0
Time: 851ms
like image 386
Blaze Avatar asked Dec 09 '16 12:12

Blaze


1 Answers

As can be seen from webpack config file, I was creating a common vendor script for multiple vendor libraries. On checking, I found that this vendor file was included at two places in html DOM.

Though it's not clear why inclusion of vendor scripts at multiple places caused the user script to execute twice - for now my problem is solved, after removing multiple inclusions.

I am facing issue with integrating jquery in my typescript file, so I got it separated from vendor.bundle.js and now I am including it separately.

If anyone know about the reason behind this whole scenario then please explain it to us as well. Thanks.

like image 153
Blaze Avatar answered Oct 09 '22 19:10

Blaze