如何在Angular + templateCache中使用Webpack?

Ima*_*ost 16 javascript angularjs webpack

我正在学习Webpack.我用Angular创建了一个App,我使用templateCache在一个js文件中生成我所有的html视图,而不是在App中生成.它很酷.但接下来的Webpack工作:

entry: {
    app: ["bootstrap-webpack!./bootstrap.config.js", './app/app.js'],
    vendor: ['angular', 'bootstrap', 'angular-ui-router', 'oclazyload']
},
output: {
    path: path.join(__dirname, "dist"),
    filename: '/bundle.js'
},
plugins: [
    new webpack.optimize.CommonsChunkPlugin(
        /* chunkName= */ "vendor", /* filename= */ "/vendor.bundle.js"),
Run Code Online (Sandbox Code Playgroud)

这是我的webpack配置的一部分.结果我得到目录"dist"与"bundle.js"&&"vendor.bundle.js"和index.html.之后,我启动服务器,我的应用程序说它无法获取视图.为什么?:(据我所知,我的所有观点都必须捆绑在一起,并且应该在"dist"目录中提供.

Joh*_*ald 23

我根本不用templateCache.由于Angular指令也接受模板作为字符串,我只是require()带有html-loader的模板.

function MyDirective() {
    return {
        restrict: "E",
        replace: true,
        template: require("./MyDirective.html")
    };
}
Run Code Online (Sandbox Code Playgroud)
// in your webpack.config.js
module.exports = {
    module: {
        loaders: [
            { test: /\.html$/, loaders: ["html"] }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 他们可能不知道^^.AngularJS 1.0有很多不必要的东西.例如,如果您没有看到依赖注入的好处,那么整个模块系统就是残留的 (2认同)
  • 使用html-loader不会复制HTML代码.该模块仅包含一次. (2认同)
  • 对不起,这是不正确的.HTML源代码肯定只包含一次.如果您正在使用代码分割,那么HTML可能会包含在几个块中,但这适用于webpack中的所有模块. (2认同)

jan*_*bee 8

为时已晚,但不妨分享一下。如果您真的想使用html片段,也许

<div ng-include="'file.tplc.html'"></div>
Run Code Online (Sandbox Code Playgroud)

这就是我的工作方式

var appMod = angular.module('app'); 

appMod.run(function($templateCache) {

    function requireAll(requireContext) {
        return requireContext.keys().map(function(val){
            return {
                // tpl will hold the value of your html string because thanks to wepbpack "raw-loader" **important**
                tpl:requireContext(val),

                //name is just the filename
                name : val.split('/').pop()
            }
        });
    }

    // here "../" is my app folder root
    // tplc is the naming convention of the templates
    let modules = requireAll(require.context("../", true, /\.tplc\.html$/));

    modules.map(function (val) {
        $templateCache.put(val.name, val.tpl);
    })

});
Run Code Online (Sandbox Code Playgroud)