如何使用 webpack 要求或仅从模块导入必要的导出

How to require or import only necessary exports from module with webpack

本文关键字:导入 模块 webpack 何使用      更新时间:2023-09-26

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

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

在另一个模块中,我只想要求config.common对象,但避免代码config.server命中到客户端捆绑包中。这在 webpack 中可能吗?

被称为"摇树",将成为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语法。