【问题标题】:angular 4, globally import external javascriptangular 4、全局导入外部javascript
【发布时间】:2017-08-21 17:19:21
【问题描述】:

我知道以前有人问过这个问题,但是在搜索和尝试了很多东西之后,我不得不问。

我正在使用Angular Starter 包并尝试导入external javascript library

像这样直接将它导入到我的组件中没有问题

import * as loadImage from 'blueimp-load-image/js/index.js';

但据我所知,我应该在 zone.js 之前导入外部脚本(使用异步操作),否则可能会导致更改检测出现问题。 事实上,这正是我在 iOS 中使用 Safari 时遇到的问题。目前我必须手动调用更改检测。

在 angular starter 包中,polyfills.ts 文件中需要 zone.js,该文件由 webpack 作为 chunk/js 文件添加。

import 'blueimp-javascript-to-blob-for-angular';
//how to import so it's useable in any component?
import 'blueimp-load-image/js/index';
import 'core-js/es6';
import 'core-js/es6/set';
import 'core-js/es7/reflect';

require('zone.js/dist/zone');

if ('production' !== ENV) {
    Error['stackTraceLimit'] = Infinity;
    require('zone.js/dist/long-stack-trace-zone');
}

如何以及在哪里可以在 zone.js 之前导入我的外部 javascript 文件(以下内容),以便我仍然可以在我的组件中使用它?

到目前为止,我的问题是我无法访问外部库函数,因为它们总是undefined。但它们已被添加到生成的 javascript 文件中。

将外部javascript导入angular 4项目的整个过程对我来说似乎很复杂。

Javascript 文件内容:

module.exports = require('./load-image')

require('./load-image-scale')
require('./load-image-meta')
require('./load-image-fetch')
require('./load-image-exif')
require('./load-image-exif-map')
require('./load-image-orientation')

【问题讨论】:

标签: angular webpack


【解决方案1】:

如果您使用的是AddAssetHtmlPlugin,如图所示here

  /**
   * Plugin: AddAssetHtmlPlugin
   * Description: Adds the given JS or CSS file to the files
   * Webpack knows about, and put it into the list of assets
   * html-webpack-plugin injects into the generated html.
   *
   * See: https://github.com/SimenB/add-asset-html-webpack-plugin
   */
  // new AddAssetHtmlPlugin([
  //   { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('polyfills')}`) },
  //   { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('vendor')}`) }
  // ]),

您需要创建另一个 entryhere,这将需要外部 js 文件并在其他捆绑包之前使用 AddAssetHtmlPlugin 插件加载。

【讨论】:

  • 我刚试过。它可以工作并添加必要的 JS 文件(只需要排除 SourceMaps)。但老实说,在我的书中,导入 Js 文件不应该这么难(我花了几个小时尝试不同的方法)。虽然这种方法有效,但我认为它远非理想。总之感谢。但是 webpack 现在在导入文件的第 1 行抱怨 Uncaught ReferenceError: module is not defined
  • 所以可能需要将这个 ES6 模块转译成浏览器可以理解的东西……哦,天哪……
  • @Arikael,到底有什么难的?您正在使用构建工具,您应该使用它支持的方法。您需要一个新的入口点,因为 ESM 模块是静态的,并且在执行导入它们的模块之前执行。最后一个错误可能是一个单独的问题。如果 Webpack 配置正确,它将把 module 转换成它自己的 require 格式
【解决方案2】:

在 index.html 文件的 head 部分中导入外部 javascript 文件,该部分是应用程序的入口点,使用普通的 html 脚本标签 示例:

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>

【讨论】:

  • 但这会导致额外的请求。
  • 是的.. 但是当 index.html 页面(即您的单页应用程序)加载到浏览器时,它只会加载一次外部 javascript 文件@Arikael
  • 没有办法将它直接包含到应用程序中(导入/需要等?)
  • 您可以在您将要使用它的应用程序的 html 模板中添加相同的脚本标签。 @Arikael。您不能在 .ts 文件中导入 javascript 文件,因为 .ts 是 typescript 文件,而 .js 是 javascript。因此,您要么必须在 html 模板或 index.html 文件中导入所有外部 .js 文件
猜你喜欢
  • 2018-04-25
  • 2018-04-07
  • 2019-01-20
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 2018-01-07
相关资源
最近更新 更多