繁体   English   中英

导入内联js脚本Webpack

[英]Import inlined js script webpack

我正在使用Webpack编写Angular应用程序。

我有一个用户个人资料JavaScript对象,我想通过一个内联脚本将其模板化到索引页面中,以提高性能,从而使客户端不必再提出其他请求并延迟其余页面的加载。

使用requirejs可以命名一个内联模块,以便以后使用它。 有什么办法可以做这个webpack吗? 还是我坚持要宣布它为全球性产品?

例如,这是您可以在Require JS中执行的操作;

<html>
<body>
...
<script>
define('userProfile', [
  'angular'
], function(angular) {
  return angular.module('userProfile', [])
    .constant('userProfile', Object.freeze({
      id: '$!{user.userid}',
      name: '$!{user.fullname}',
      userType: '$!{user.userType}'
    }))
});
</script>
...
</body>
</html>

在提供索引页面时,将使用诸如'$!{user.userid}'类的用户字段作为模板。

要在您的应用程序中依赖于此,您可以简单地执行以下操作

define([
    'userProfile',
], function() {    
  return angular.module('my-app', [
        'userProfile',
  ]);
});

您可以在webpack配置中将变量或模块指定为外部变量,以便仅通过脚本标签将其包含在页面上。 这是我跳过与脚本捆绑的库的操作

// webpack.config.js
 "externals": {
            "jquery": "jQuery",
            "angular": "angular"
        },

但是作为有角度的作品,您不需要使用webpack导入模块

<script>
(function(angular) {
  angular.module('userProfile', [])
    .constant('userProfile', Object.freeze({
      id: '$!{user.userid}',
      name: '$!{user.fullname}',
      userType: '$!{user.userType}'
    }))
})(angular);
</script>

在您的模块中,您可以。

angular.module('whatever', ['userProfile'])

现在,您可以在角度应用程序中的任何位置使用用户配置文件常数。

angular.module('whatever').controller(['userProfile', function (userProfile) {}]);

您只需要确保在捆绑包之前执行了userProfile脚本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM