欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解如何使用webpack+es6开发angular1.x

程序员文章站 2022-09-08 13:42:48
虽然,现在越来越多的人选择使用react、vue以及ng2,但是依然存在相当一部分人在使用angular1.x开发。本文将介绍如何使用webpack+es6+angular...

虽然,现在越来越多的人选择使用react、vue以及ng2,但是依然存在相当一部分人在使用angular1.x开发。本文将介绍如何使用webpack+es6+angular1.x+$oclazyload实现动态加载。

1.webpack

webpack.config.js

var path = require('path');

var webpack = require('webpack');

var extracttextplugin = require("extract-text-webpack-plugin");

module.exports = {
  entry: {
     home: [
        'babel-polyfill',
         './app/app.js'      //引入文件
      ],
      common: [
           'babel-polyfill',
           'angular', 
            'angular-ui-router', 
            'oclazyload'
        ]
   },
   output: {
     path: path.join(__dirname, '/wap'),
     filename: '[name].js',
     chunkfilename: '[id].build.js?[chunkhash]',
     publicpath: '/wap/',
   },
   module: {
     loaders: [
       {
           test:/\.js?$/,
           loader:'ng-annotate-loader!babel-loader',
           exclude:/node_modules/
       },
       {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: /node_modules/
       },
     ]
  },
  resolve: {
       root: ['node_modules'],
       extensions: ['', '.js', '.html', '.json'],
       modulesdirectories: ['node_modules'],
       alias: {}
   },
  externals: {},
  plugins: [
          new webpack.hotmodulereplacementplugin(),
          new extracttextplugin('[name].[contenthash:20].css'),
          new webpack.optimize.uglifyjsplugin({
               compress: {warnings: false},
               sourcemap: true
          }),
         new webpack.optimize.commonschunkplugin('common', 'common.js')
  ]

}

2.module

第一步,先引入angular ,以及相关模块,然后像es5中那样定义一个模块

app.js

import angular from 'angular';
import uirouter from 'angular-ui-router';
import oclazyload from 'oclazyload';
angular.module('app',[ uirouter,oclazyload ])

模块与模块之间引用

我们建立第二个模块 header/index.js

import angularfrom 'angular';
export default angular.module('header',[]).name

修改app.js

import header from './header'
angular.module('app',[ uirouter,oclazyload , header])

模块的引用完成

3.控制器

假设在header目录下新增一个控制器

header/controller.js

export default class headercontroller {
     consturctor(){
         this.home = 'header'
      }
}

引用控制器 修改 header/index.js

import headercontroller from './controller'
export default angular.module('header',[ ])
   .controller('headercontroller',headercontroller)
   .name

4.服务

如果要在控制器内使用$scope,或者其他服务肯定是报错的,那是因为我们在使用之前没有注入服务

所以第一步应该注入服务

header/controller.js

export default class headercontroller {
   consturctor($scope){
       this.home = 'header'
       $scope.component = 'head'
    }
}
headercontroller.$inject = ['$scope']

那么如何自定义服务呢?

新建 header.server.js

class headerservices {
     constructor(){
          this.name = 'cxh'
     }
     getname(){
          return this.name
     }
}

header/index.js

import headerservice from './service';
export default angular.module('header',[ ])
     .controller('headercontroller',headercontroller)
     .service('headerservice',headerservice)
     .name

在控制器中使用自定义服务

header/controller.js

export default class headercontroller {
    consturctor($scope,headerservice){
         this.home = 'header'
         $scope.component = 'head'
         $scope.name = headerservice.getname
     }
}
headercontroller.$inject = ['$scope','headerservice']

5.指令

新建 footer/index.js 大致和 header/index.js相同

将 footer模块 引入到 app.js

新建footer/directive.js

export default class footer {
     constructor(){
          this.restrict = 'e',
          this.scope = {},
          this.template = "<div ng-click='alert()'>footer</div>"
          this.controller = foot
          this.link = (scope, element, attr) => {}
     }
}
class foot{
       constructor(){
         $scope.alert = () => { alert(1) } 
       }
}
header.$inject = ['$scope']

footer/index.js

export default angular.module('footer',[])
.directive('footerdirective',()=> new footer)
.name

6.路由

router.js

export default router ($stateprovider, $urlrouterprovider) {
    $stateprovider.state("home",{ 
           url:"/home",
           templateurl:'app/home/home.html',
           controller: "homecontroller",
           controlleras:"hmc",
     })
    $urlrouterprovider.otherwise('/home');
}
router.$inject = [ '$stateprovider', '$urlrouterprovider']

demo 实现动态加载

1.第一步,新建app.js创建一个module

import angular from 'angular';
import uirouter from 'angular-ui-router';
import oclazyload from 'oclazyload';
//引用创建头部 组件
import header from './header';
//路由
import routing from "./router.js";
//引入两个子模块
import home from "./homes";
import router from "./router";

angular.module('app',[uirouter, header, oclazyload, home, router])
.config(routing)

2.配置路由 ./route.js

export default function routing($stateprovider, $urlrouterprovider) {
 'nginject'; //注入服务 就不需要使用$inject了
 $stateprovider
   .state("home",{
      url:"/home",
      templateprovider: ($q) => {   //动态引入html模板
        'nginject';
        let deferred = $q.defer();
        require.ensure([], function () {
          let template = require('./home/home.html');
          deferred.resolve(template);
        });
        return deferred.promise;
       },
       controller: "homecontroller",
       controlleras:"hmc",
       resolve: {      //动态加载模块
         loadmyctrl: function ($q, $oclazyload) {
            'nginject';
            let deferred = $q.defer();
            require.ensure([], () => {
                let module = require("./home").default;
                $oclazyload.load({name: module.name});
                deferred.resolve(module.controller)
             });
            return deferred.promise;
          }
      }
   }),
   .state("route",{
     url:"/route",
     templateprovider: ($q) => {   //动态引入html模板
        'nginject';
        let deferred = $q.defer();
        require.ensure([], function () {
            let template = require('./router/router.html');
            deferred.resolve(template);
         });
         return deferred.promise;
      },
      controller: "routercontroller",
      controlleras:"rtc",
      resolve: {      //动态加载模块
         loadmyctrl: function ($q, $oclazyload) {
           'nginject';
            let deferred = $q.defer();
            require.ensure([], () => {
               let module = require("./router").default;
               $oclazyload.load({name: module.name});
               deferred.resolve(module.controller)
            });
            return deferred.promise;
       }
   }
 })
$urlrouterprovider.otherwise('/home');
}

3.header

header/index.js

import angular from "angular";
import header from './directive';
export default angular.module('app_header',[])
     .directive('header', () => new header)
     .name;

header/directive.js

class header {
 constructor($scope){
  'nginject';
  $scope.isshow = false;
 }
}
export default class header {
  constructor() {
    this.restrict = 'e',
    this.scope = {},
    this.template = require(./header.html) 
    this.controller = header
    this.link = (scope, element, attr) => {}
  }
}

header/header.html

<div>
   <a href="#home" rel="external nofollow" >home</a>
   <a href="#router" rel="external nofollow" >router</a>
</div>

4.home

home/index.js

import angular from "angular";
import homecontroller from './controller';
export default angular.module('app_home',[])
     .controller('homecontroller', homecontroller)

home/controller.js

export default class homecontroller {
 constructor($scope) {
  'nginject';
  this.isshow = false;
  this.eage = 'sds';
  $scope.edg = 'sma'
 }
 change(){
   this.isshow = !this.isshow;
   console.log(this.isshow);
  }
}

home/home.html

<div>home {{hmc.eage}} -- {{edg}}</div>

其余的模块大同小异就不依依去写了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。