【问题标题】:How to require or import only necessary exports from module with webpack如何使用 webpack 从模块中仅需要或导入必要的导出
【发布时间】:2016-04-27 09:51:31
【问题描述】:

例如我有一些配置的模块:

exports.common = {
	cookieDomain: '.mydomain.dev',
	protocol: 'http',
	apiPort: 3030
}

exports.server {
	port: 8080
}

在另一个模块中,我只想要求 config.commonobject,但要避免 config.server 中的代码进入客户端包。使用 webpack 可以做到这一点吗?

【问题讨论】:

  • 如果我没记错的话,这将在 webpack 2(目前处于测试阶段)中成为可能,但仅限于 ES2015 语法。
  • 并非如此。如果您不需要它们,请不要将它们放在同一个模块中。

标签: javascript ecmascript-6 webpack commonjs es6-module-loader


【解决方案1】:

这称为“摇树”和will be a part of webpack 2。 但是你不能使用 CommonJS 语法,你需要使用 ES2015 模块语法:

出口:

export const common = {
    cookieDomain: '.mydomain.dev',
    protocol: 'http',
    apiPort: 3030
};

export const server {
    port: 8080
};

进口:

import common from 'config';

common; // do something with common
// server is not included in the bundle

您可以使用当前版本号安装测试版:

npm install webpack@2.1.0-beta.6

或者,您也可以查看rollup.js,它从一开始就支持此功能(并且还生成了更小的捆绑包)。它也只支持 ES2015 语法。

【讨论】:

  • 我安装了 webpack 2,但它并没有动摇树。我怀疑问题出在已安装的预设或插件中。下面是我的 .babelrc { "presets": ["react", "es2015", "stage-0", "es2015-loose", "es2015-native-modules"], "plugins": [ "transform-runtime", "transform-decorators-legacy", "transform-class-properties" ], "sourceMaps": true, "retainLines": true }
  • 去掉es2015es2015-loose,否则你的imports会被转译成require();s。
  • 我无法删除 es2015,因为 nodejs 上的服务器端抛出错误 SyntaxError: Unexpected token import
  • 使用es2015-native-modules?
  • 不,它不小心到了这里
猜你喜欢
  • 1970-01-01
  • 2019-11-10
  • 2020-03-02
  • 1970-01-01
  • 2017-12-01
  • 2019-12-05
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多