【问题标题】:How to use Webpack with Angular + templateCache?如何将 Webpack 与 Angular + templateCache 一起使用?
【发布时间】:2023-03-28 05:10:01
【问题描述】:

我正在学习 Webpack。我用 Angular 制作了一个应用程序,我使用 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"),

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

【问题讨论】:

    标签: javascript angularjs webpack


    【解决方案1】:

    我根本不使用templateCache。由于 Angular 指令也接受模板作为字符串,所以我只使用 require()html-loader 的模板。

    function MyDirective() {
        return {
            restrict: "E",
            replace: true,
            template: require("./MyDirective.html")
        };
    }
    

    // in your webpack.config.js
    module.exports = {
        module: {
            loaders: [
                { test: /\.html$/, loaders: ["html"] }
            ]
        }
    }
    

    【讨论】:

    • 他们可能不知道^^。 AngularJS 1.0 有很多不必要的复杂的东西。例如,如果你没有看到依赖注入的好处,那么整个模块系统就很糟糕
    • 存在模板加载器,以便您可以预编译模板并使其在运行时可用,而不是像这种方法所要求的那样在运行时编译它们。
    • 使用 html-loader 不会复制 HTML 代码。该模块只会被包含一次。
    • 如果您对多个组件使用相同的模板(出于任何原因),则会重复该模板。另外这种方法的缺点是,如果要迁移到 webpack 现有项目,则需要重写 templateUrl -> 模板的所有入口
    • 对不起,这不正确。 HTML 源代码肯定只包含一次。如果您使用的是代码拆分,可能是 HTML 将包含在几个块中,但这适用于 webpack 中的所有模块。
    【解决方案2】:

    它已经晚了,但不妨分享一下。如果你真的想使用 html 片段,也许是为了

    <div ng-include="'file.tplc.html'"></div>
    

    这就是我的工作方式

    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);
        })
    
    });
    

    【讨论】:

    • 只是为了澄清:您的代码是通过调用“webpack”还是在启动应用程序时触发的?
    • require.contextwebpack 触发。一旦应用程序被上下文函数返回的内容(另一个函数)引导,该函数的其余部分将运行。
    猜你喜欢
    • 1970-01-01
    • 2015-09-15
    • 2016-11-23
    • 1970-01-01
    • 2021-12-05
    • 2017-12-09
    • 2020-10-05
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多