使用webpack导入angularjs的最佳实践是什么?

JavaScript Webpack

神乐

2020-03-24

如何将Webpack和AngularJS一起使用,如何加载模板和按需获取资源?

一个非常好的webpack.config.js为此目的编写文件的示例将不胜感激。

此处显示的所有代码段均可在此github存储库中访问代码已从此packetloop git repo大量修改

webpack.config.json

var path = require('path');
var ResolverPlugin = require("webpack/lib/ResolverPlugin");

var config = {
  context: __dirname,
  entry: ['webpack/hot/dev-server', './app/app.js'],
  output: {
    path: './build',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.css$/,
      loader: "style!css-loader"
    }, {
      test: /\.scss$/,
      loader: "style!css!sass?outputStyle=expanded"
    }, {
      test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$/,
      loader: "file"
    }, {
      test: /\.html$/,
      loader: "ngtemplate?relativeTo=" + path.join(__dirname, 'app/') + "!raw"
    }]
  },
  // Let webpack know where the module folders are for bower and node_modules
  // This lets you write things like - require('bower/<plugin>') anywhere in your code base
  resolve: {
    modulesDirectories: ['node_modules', 'lib/bower_components'],
    alias: {
      'npm': __dirname + '/node_modules',
      'vendor': __dirname + '/app/vendor/',
      'bower': __dirname + '/lib/bower_components'
    }
  },
  plugins: [
    // This is to help webpack know that it has to load the js file in bower.json#main
    new ResolverPlugin(
      new ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
    )
  ]
};

module.exports = config;

要将AngularJS导入主体,app.js请执行以下操作:

app / vendor / angular.js

'use strict';

if (!global.window.angular) {
  require('bower/angular/angular');
}
var angular = global.window.angular;
module.exports = angular;

然后app.js像这样使用它

app.js

...
var angular = require('vendor/angular');

// Declare app level module
var app = angular.module('myApp', []);

...

以下正确吗?有没有更简单的方法可以做到这一点?我看过几篇文章(按任何标准来看都不多),其中列出了另一种方法。

这个reddit帖子评论

// Add to webpack.config.js#module#loaders array
    {
      test: /[\/]angular\.js$/,
      loader: "exports?angular"
    }

There is also another plugin which is in development right now, at stackfull/angular-seed. It seems to be in the right direction, but is really really hard to use right now.

Webpack is way awesome, but the lack of documentation and samples are killing it.

第3280篇《使用webpack导入angularjs的最佳实践是什么?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android