Webpack 2异常 - 未捕获的ReferenceError:未定义webpackJsonp

时间:2017-02-06 13:05:33

标签: angular webpack webpack-2

我正在使用webpack 2,并且我执行了浏览器中的webpack-dev-server

例外:“未捕获的ReferenceError:未定义webpackJsonp。”

当我尝试创建供应商块时,此异常开始。

我的webpack.config.js文件:

    'use strict';

const webpack = require('webpack');
const path = require('path');
const webpackMerge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');


// Webpack Config
let webpackConfig = {
    entry: {
        'main': './src/main.ts',
        'vendors': './src/vendors.ts'
    },
    target: 'web', //https://webpack.js.org/configuration/target/
    output: {
        publicPath: '',
        path: path.resolve(__dirname, './dist')
    },

    plugins: [
        new CleanWebpackPlugin(['./dist'], {
            verbose: true,
            dry: false
        }),


        new CommonsChunkPlugin({
            names: ['vendors'],
            filename: '[name].js'
        }),


        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
            path.resolve(__dirname, './src'),
            {
                // your Angular Async Route paths relative to this root directory
            }
        )
    ],

    module: {
        rules: [
            {
                enforce: 'pre',
                test: /\.ts$/,
                loader: 'tslint-loader',
                exclude: /(node_modules)/
            },
            {
                test: /\.ts$/,
                use: [
                    'awesome-typescript-loader',
                    'angular2-template-loader',
                    'angular2-router-loader'
                ]
            },
            {
                test: /\.scss$/,
                use: ['to-string-loader', 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader']
            },
            {
                test: /\.css$/,
                use: ['to-string-loader', 'css-loader']
            },
            {
                test: /\.html$/,
                use: 'raw-loader'
            }
        ]
    }

};


// Our Webpack Defaults
let defaultConfig = {
    devtool: 'source-map',

    output: {
        filename: '[name].bundle.js',
        sourceMapFilename: '[name].map',
        chunkFilename: '[id].chunk.js'
    },

    resolve: {
        extensions: ['.ts', '.js'],
        modules: [path.resolve(__dirname, 'node_modules')]
    },

    devServer: {
        historyApiFallback: true,
        watchOptions: {aggregateTimeout: 300, poll: 1000},
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
            "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
        }
    },

    node: {
        global: true,
        crypto: 'empty',
        __dirname: true,
        __filename: true,
        process: true,
        Buffer: false,
        clearImmediate: false,
        setImmediate: false
    }
};


module.exports = webpackMerge(defaultConfig, webpackConfig);

我的package.json

    {
  "name": "infra-template-ng-2",
  "version": "1.0.0",
  "description": "A infra template for Angular2",
  "license": "MIT",
  "homepage": "https://ilgitlab/sizmek-ui-infra/infra-angular-tow-template/tree/master",
  "scripts": {
    "build": "webpack --progress",
    "watch": "npm run build --watch",
    "server": "webpack-dev-server --inline --progress --colors --port 3000 --content-base src --open",
    "start": "npm run server"
  },    
  "dependencies": {
    "@angular/common": "~2.4.6",
    "@angular/compiler": "~2.4.6",
    "@angular/compiler-cli": "~2.4.6",
    "@angular/core": "~2.4.6",
    "@angular/forms": "~2.4.6",
    "@angular/platform-browser": "~2.4.6",
    "@angular/platform-browser-dynamic": "~2.4.6",
    "angular2-ui-switch": "^1.2.0",
    "core-js": "~2.4.1",
    "ie-shim": "~0.1.0",
    "reflect-metadata": "~0.1.9",
    "rxjs": "~5.1.0",
    "zone.js": "~0.7.6"
  },
  "devDependencies": {
    "@types/node": "^6.0.48",
    "angular2-router-loader": "^0.3.4",
    "angular2-template-loader": "^0.6.0",
    "awesome-typescript-loader": "^3.0.3",
    "clean-webpack-plugin": "^0.1.15",
    "codelyzer": "^2.0.0-beta.4",
    "css-loader": "^0.25.0",
    "json-loader": "^0.5.4",
    "node-sass": "^4.3.0",
    "postcss-loader": "^1.2.2",
    "raw-loader": "^0.5.1",
    "sass-loader": "^4.1.1",
    "source-map-support": "^0.4.11",
    "style-loader": "^0.13.1",
    "to-string-loader": "^1.1.4",
    "tslint": "^4.4.1",
    "tslint-loader": "^3.3.0",
    "typescript": "~2.1.5",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.2.1",
    "webpack-merge": "^2.6.1"
  },
  "keywords": [
    "Angular 2 Infra Template"
  ],
  "repository": {
    "type": "git",
    "url": "git@ilgitlab:sizmek-ui-infra/infra-angular-tow-template.git"
  }
}

我的tsconfig.json

    {
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "outDir": "dist",
        "rootDir": ".",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es6",
            "dom"
        ]
    },
    "exclude": [
        "node_modules"
    ],
    "awesomeTypescriptLoaderOptions": {
        "useWebpackText": true
    },
    "angularCompilerOptions": {
        "debug": false
    },
    "compileOnSave": false,
    "buildOnSave": false,
    "atom": {
        "rewriteTsconfig": false
    }
}

my vendors.ts

import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/compiler';
import '@angular/common';
import '@angular/http';
import '@angular/forms';

我的index.html

    <!DOCTYPE html>
<html>
  <head>
    <meta charset=UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Infra Template</title>
    <base href="/">
  </head>
  <body>

    <infra-app>
      Loading...
    </infra-app>

        <script async src="vendors.js"></script>
        <script async src="main.bundle.js"></script>

  </body>
</html>

2 个答案:

答案 0 :(得分:10)

运行期间,当webpackJsonp函数未定义(显然)嘿嘿时,会发生此错误,但这是什么意思?

因此webpack中有三种类型的块:

Chunks diagram

通过CommonsChunkPlugin创建初始块,以提高可缓存性,但是它们是同步加载的,并依赖于webpack运行时(aka entry chunk)中定义的webpackJsonp函数。

tl; dr你的脚本是乱序加载的。如果您使用的是html-webpack-plugin,则可以在配置中使用他们的chunkSort选项来解决此问题。这通常也可以通过多个CommonsChunkPlugin的模糊组合来实现。

我最好的建议是删除CommonsChunkPlugin并只创建一个bundle,然后一个一个地将所需的代码逐个拆分成单独的bundle,以发现排序问题发生的位置。

答案 1 :(得分:0)

vendor.js

中加入index.html

这里是完整的HTML代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.log('Error', err));
    }
  </script>-->
  <!-- The vendor js is generated during the build process
      It contains all of the dependencies in node_modules -->
  <script src="build/vendor.js"></script>
  <!-- The main bundle js is generated during the build process -->
  <link href="build/main.css" rel="stylesheet">

</head>

<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The vendor js is generated during the build process
       and includes all files in the node_modules directory -->
  <script src="build/vendor.js"></script>

  <!-- The bundle js is generated during the build process -->
  <script src="build/main.js"></script>

</body>
</html>