Script created by webpack executing twice

时间:2016-12-09 12:42:50

标签: javascript ajax reactjs typescript webpack

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 typescript@2.1.4 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

1 个答案:

答案 0 :(得分:3)

从webpack配置文件中可以看出,我正在为多个供应商库创建一个通用的供应商脚本。在检查时,我发现这个供应商文件包含在html DOM的两个地方。

虽然不清楚为什么在多个位置包含供应商脚本导致用户脚本执行两次 - 现在我的问题在删除多个包含后解决了。

我遇到了将jquery集成到我的打字稿文件中的问题,所以我将它与vendor.bundle.js分开,现在我将其单独包含在内。

如果有人知道这个场景背后的原因,那么请向我们解释一下。感谢。