Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

记一次 import 打包 印象误区 #672

Open
libin1991 opened this issue Nov 26, 2018 · 0 comments
Open

记一次 import 打包 印象误区 #672

libin1991 opened this issue Nov 26, 2018 · 0 comments

Comments

@libin1991
Copy link
Owner

问题

今天写项目看到一个问题很有意思。先抛出一个问题,哪个写法性能高?

  • 第一种写法

a.js:

export const a = '1';
export const b = '2';
export const c = '3';
export const d = '4';
复制代码

b.js:

import {a, b} from './a';
console.log(a, b);
复制代码
  • 第二种写法

a.js:

export const a = '1';
export const b = '2';
export const c = '3';
export const d = '4';
复制代码

b.js:

import * as obj from './a';

console.log(obj.a, obj.b);
复制代码

  • 第三种写法:

a.js

export default {
    a: '1',
    b: '2',
    c: '3',
    d: '4'
}
复制代码

b.js

import obj from './a';

console.log(obj.a, obj.b);
复制代码

这个问题对于没有深刻了解过 webpack 打包原理机制的我来说还真的有点迷了。所以决定这段时间去好好研究一波。

测试

我们的测试很简单:

配置一个 webpack4 的环境

建立了 a.js, b.js 然后就这么写,然后打包,就这么简单。

  • "webpack": "^4.26.1"

  • "webpack-cli": "^3.1.2"

上图

第一种

a.js

b.js

第二种

a.js

b.js

第三种

a.js

b.js

结论

我们看到 第一种 和 第二种 写法 打包出来 完全一样.至于第三种,其实就是包了一层 default Object 而已。再来一张图。

所以其实三种写法 并没有多大卵区别,非说有的话。。。那就是第三种多了一层 obj 吧。如果您有更深刻的理解欢迎 评论。分享无罪,欢迎组队

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant