如何使用Django,Angular2和Webpack版本代码?

时间:2016-08-02 11:17:32

标签: javascript angularjs django angular webpack

我正在使用Django + Angular 2 + Webpack,在Django中我创建了一个URL来渲染我的应用程序(http://example.com/user/beta),所以首先我的index.html得到渲染& index包含我的angular 2东西,因为我使用的是webpack,所有东西都捆绑在main,vendor& polyfill,我的结构是这样的:

app
 |
 |__angular
 |     |
 |     |
 |     |___src
 |     |___typings
 |     |___package.json, tsconfig.json, webpack.config.js
 |
 |
 |__static
 |     |__css
 |     |__dist <this contains bundle files which got complied by webpack>
 |
 |
 |__templates
 |     |
 |     |___index.html
 |     |___app
            |__<all template files>

这里所有静态文件都存储到CDN&amp;在那里似乎js文件正在缓存所以新的更改没有反映,为了避免我必须手动版本我的js文件,如main.bundle.v.01.js,我想每次我想要将其部署到测试/生产时更改捆绑文件版本,所以这个手动工作消失了,为此我必须在webpack.config中进行一些更改以进行版本控制。将它们放在index.html中,但由于index.html不能控制无法完成的webpack,所以我需要找到一种方法,webpack解析角度应用程序代码也会对这些bundle文件进行版本控制。在index.html中替换它

1 个答案:

答案 0 :(得分:1)

我使用的解决方案可以在以下模板中找到

https://github.com/dkarchmer/django-aws-template

不幸的是,它基于Gulp(不是Webpack),但您应该能够轻松地从Webpack模拟相同的流(或切换到Gulp)。

基本上,我的webapp的gulp流程的最后一步是使用常规印象来修改Gulp生成的顶级index.html,并将其移动到模板目录:

gulp.task('templates', ['build'], () => {
  // Black Magic to convert all static references to use django's 'static' templatetags
  return gulp.src(config.dist + '/*.html')
        .pipe(replace(/href="app([/]\S*)"/g, 'href="{% static \'dist/webapp/app$1\' %}"'))
        .pipe(replace(/src="app([/]\S*)"/g, 'src="{% static \'dist/webapp/app$1\' %}"'))
        .pipe(gulp.dest(config.templates));
});

其中config.templates = '../server/templates/dist/webapp'。显然,您还需要.gitignore此目录。你最终得到了

如您所见,我基本上用href=app/foo/bar

替换任何href={% static 'dist/webapp/app/foo/bar' %}

我这样做,因为我仍然希望能够在我的本地计算机上进行开发时更改{% static %}模板标记,以及静态来自生产中的CDN。

您将在django模板上注意到的另一件事是基础模板server/templates/base.html

扩展而来
{% extends "dist/webapp/index.html" %}

dist/webapp/index.html是我的Gulp流程复制修改后的index.html的地方。对于图像源文件也是如此。或者在您的流程中,也许您可​​以将{% static %}保留在源文件上,并让webpack处理它们。

|__templates
|     |
|     |__dist
|     |     |
|     |     |__ webapp/index.html
|     |
|     |___base.html

就我而言,Gulp流程严格处理样式表和脚本,其余部分由base.html使用常规Django技术完成。

在我使用Angular的另一个项目中,但是仍然希望使用Django来渲染和处理登录和权限,我添加了一个基本上没有的视图

class AngularView(TemplateView):
    template_name = 'dist/webapp/index.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(AngularView, self).dispatch(request, *args, **kwargs)

其中'dist/webapp/index.html'也是由Gulp流构建和复制的修改文件(不受版本控制)。

显然,缺点(至少对某些人来说)是你现在有两个步骤:1)Build Statics,以及2)Django。但对我来说,这相当于python manage.py collectstatic无论如何都有效。