【问题标题】:Is there any benefit to import the entire module before importing part of it?在导入部分模块之前导入整个模块有什么好处吗?
【发布时间】:2016-01-05 04:29:11
【问题描述】:

目前我正在研究项目angular2-webpack-starter。它的webpack.config.js 有两个条目:main.tsvendor.ts

main.ts

import {provide} from 'angular2/core';
import {bootstrap, ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';

import {App} from './app/app';

document.addEventListener('DOMContentLoaded', function main() {
  bootstrap(App, [
    ...('production' === process.env.ENV ? [] : ELEMENT_PROBE_PROVIDERS),
    ...HTTP_PROVIDERS,
    ...ROUTER_PROVIDERS,
    provide(LocationStrategy, { useClass: HashLocationStrategy })
  ])
  .catch(err => console.error(err));
});

vendor.ts

// Polyfills
import 'es6-shim';
// (these modules are what are in 'angular2/bundles/angular2-polyfills' so don't use that here)
import 'es6-promise';
import 'zone.js/lib/browser/zone-microtask';

if ('production' !== process.env.ENV) {
  // Reflect Polyfill
  require('es7-reflect-metadata/dist/browser');
  Error['stackTraceLimit'] = Infinity;
  Zone['longStackTraceZone'] = require('zone.js/lib/zones/long-stack-trace.js');
}

if ('production' === process.env.ENV) {
  // Reflect with es7-reflect-metadata/reflect-metadata is added
  // by webpack.prod.config ProvidePlugin
  let ngCore = require('angular2/core');
  ngCore.enableProdMode();
}
// Angular 2
import 'angular2/platform/browser';
import 'angular2/platform/common_dom';
import 'angular2/router';
import 'angular2/http';
import 'angular2/core';

// RxJS
import 'rxjs';

我了解vendor.js 是导入依赖项。但是为什么这里要导入 angular2 模块呢?由于它们也被导入到其他文件(如main.ts)中,因此似乎没有必要两次或提前导入它们。

【问题讨论】:

  • 保持依赖解析隔离。
  • @binariedMe 你能详细解释一下吗?
  • 不太确定我的逻辑,所以我将其作为评论。但是在 main.ts 和 vendor.ts 中导入相同文件的用法是 main.ts 可以在其他一些地方使用,也可以在没有其他代码使用该文件的地方使用。假设 main.ts 正在 vendor.ts 和 vendor1.ts 中导入。 main.ts 有一个 import angular2/angular2,vendor.ts 有一个 import angular2/angular2,vendor1.ts 有一个 import angular2/SomeOtherModule。现在 main.ts 的 angular2 不会与 SomeOtherModule 产生任何冲突。

标签: webpack angular


【解决方案1】:

我想我明白了。根据 webpack 的代码拆分文章,Split app and vendor code section 中解释说,在供应商文件中导入的所有依赖项都将从您的主包中排除。

这将从应用程序块中删除供应商块中的所有模块。 bundle.js 现在将只包含您的应用程序代码,没有任何依赖项。这些在 vendor.bundle.js 中。

这样你的包文件会更干净,因为所有的角度代码和所有其他库代码都将在另一个供应商文件中分开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-21
    • 2016-01-20
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多