到目前为止,我已经能够将我们所有的 Controller /指令/服务捆绑到 1 个脚本中,并且我还将所有供应商脚本捆绑到另一个脚本文件中。现在我无法弄清楚加载 AngularJS 模板文件的正确方法是什么。我们目前正在使用 Grunt,只是将确切的文件夹结构复制到 dist 文件夹,但显然这在 Webpack 中不起作用。这是我们的项目结构示例(来自 John Papa 风格指南)
我在 dist 文件夹中的项目目前呈现如下:
有人有任何意见吗?
最佳答案
AngularJS 模板是 html
文件,因此您需要添加一些加载程序来处理它们。
html
文件捆绑到 js 包中,使用 html-loader ,这种方法的优点是您的应用程序不会为模板进行 ajax 调用,缺点是您的 js 包大小会变大。这将允许您在 Controller 中“要求”您的 html 模板。
templateUrl
路径)。 .lazy.html
后缀。然后,在
.lazy.html
文件上启用 file-loader 并将其分配给 templateUrl
,并且常规一次与 template: require('template.html')
一起使用。 作为最佳实践,我会“需要”关键模板,因此它们将位于 js 包中,而延迟加载(通过
templateUrl
)非关键模板。这是
webpack.config.js
文件的示例:module.exports = {
module: {
rules: [
{
test: /\.lazy\.html$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
{
test: /\.html$/,
exclude: /\.lazy\.html$/
use: [
{
loader: 'html-loader',
options: {
minimize: true,
},
},
],
},
],
},
};
// critical.component.js
angular.
module('myApp').
component('greetUser', {
template: require('critical.html'),
controller: function GreetUserController() {
this.user = 'world';
}
});
// none-critical.component.js
angular.
module('myApp').
component('greetUser', {
templateUrl: require('non-critical.lazy.html'),
controller: function GreetUserController() {
this.user = 'world';
}
});
关于angularjs - 为 Webpack 4 加载 AngularJS 模板的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57023380/