【问题标题】:What's the best way to include templates with AngularJS + Webpack2?使用 AngularJS + Webpack2 包含模板的最佳方式是什么?
【发布时间】:2017-09-29 22:32:58
【问题描述】:

编辑:我还没有找到使用import 语句而不是require 来导入模板的方法,但我发现我可以简化我的配置。

在 webpack 配置中,使用 html-loader 而不是 ngtemplate-loader 代替 /\.html$/。然后,在组件中,像我们在原始帖子中所做的那样,在文件顶部需要模板,但是在组件定义中将“templateUrl”更改为“template”。Webpack 将完成剩下的工作你。

const template = require('./component.html');

class Example(){
    ...    
}

export const component = {
    bindings: {},
    controller: Example,
    template: template
};

原帖:

我有一个与ngtemplate-loader 合作的解决方案:

const template = require('./component.html');
import ExampleService from './example.service';

class Example() {
    constructor(private exampleService: ExampleService) {

    }
    ...
}

export const component = {
    bindings: {},
    controller: Example,
    templateUrl: template
};

但恐怕我的同事会反对require 语法。你看,我正在将我们的应用从 Grunt 迁移到 Webpack2,而当前应用只使用 import foo from './bar' 语法。

我们也不会在当前构建的 javascript 文件中导入模板;我们在 templateUrl 中使用回调来返回一个字符串。

import ExampleService from './example.service';

class Example() {
    constructor(private exampleService: ExampleService) {

    }
    ...
}

export const component = {
    bindings: {},
    controller: Example,
    templateUrl: ['constantsFactory', function(constantsFactory) {
        return `${constantsFactory.path}/component.html`;
    }]
};

有没有可以在没有require 的情况下填充 $templateCache 的 webpack 加载器?

如果没有,有没有办法在 Typescript 中使用import 语法导入模板?

【问题讨论】:

  • 这是 angular2+ 的吗?
  • 不,这是针对 AngularJS(特别是 1.5.7)

标签: javascript angularjs templates typescript webpack-2


【解决方案1】:

无法使用 import 语法将模板添加到 $templateCache,但您可以使用 'require' 语法将模板添加到缓存中。

angular1-templateurl-loader

我现在能找到的最好的加载器。

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 2023-03-11
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多