首页 > 解决方案 > 带有 Babel 和 Webpack 的 AngularJS 不加载组件控制器

问题描述

我目前正在尝试使用 AngularJS、Babel 和 Webpack 构建我的第一个项目。

我已经完成了捆绑过程,一切似乎都运行良好,我的部分 HTML 正在加载,没有错误,但是控制器似乎没有加载,

我可以在捆绑代码中看到控制器被正确捆绑,但我看不出是什么阻止了它被执行。

以下是我到目前为止所拥有的一切:

零件

import practiceTemplate from './practice.template.html';
var practiceComponent = {
    angularName: "practiceComponent",
    template: practiceTemplate,
    controller: practiceController,
    controllerAs: "practice"
}
/* @ngInject */
class practiceController {
    constructor($http) {
        this.http = $http;
        this.test = "test";
    }
    $onInit() {
        console.log(this);
        console.log("test");
        this.testGet();
    }
    testGet() {
        this.http.get("https://webhook.site/88ea9ff5-a3f7-4c50-9b81-d732d4389d3c").then(response => { console.log(response); });
    }
}
export default practiceComponent; 

模板

<article>
    <h1>Hello!</h1>

    <p>{{practice.test}}</p>
</article>

应用程序.js

import practiceComponent from './practice/practice.component';
import angular from 'angular';

angular.module("testModule", [])
    .component("practiceComponent", practiceComponent);

索引.html

<div ng-app="testModule">
    <practice-component></practice-component>
</div>

webpack.config

var path = require('path');

module.exports = {
    entry: {
        'main': path.join(__dirname, 'Scripts/src/AngularJS/app.js')
    },
    output: {
        filename: '[name]-bundle.js',
        path: path.join(__dirname, '/Scripts/dist/')
    },
    module: {
        rules: [
           {
               test: /\.js$/,
               exclude: /node_modules/,
               use: {
                loader: 'babel-loader',
                options: {
                    presets: ["@babel/preset-env"],
                    plugins: ["angularjs-annotate"]
                }
               }
           },
            {
                test: /\.html$/,
                include: path.resolve(__dirname, 'Scripts/src/AngularJS'),
                loader: 'html-loader'
            },
            {
                test: /\.styl$/,
                loader: 'style!css!stylus'
            },
            {
                test: /\.css$/,
                loader: 'style!css'
            }
        ]
    },
    target: "node"
};

标签: javascriptangularjswebpackecmascript-6babeljs

解决方案


推荐阅读