如何编写 JS 模块来导出默认和非默认函数/方法

问题描述 投票:0回答:1

我习惯在 JS 模块中编写类,如下所示:

class Auth{
  constructor() {
    init();        
  }

  init() {
    // ...
  }

  getUserData() {
    // ...
  }

  signin(username, password) {
     // ...
  }
}
export default new Auth();

然后使用 Webpack 优化我的代码。我的目标是最小化捆绑包的大小。对于某些应用程序,我不需要类中的所有方法。但大多数时候,我的方法使用

this
来共享变量。

对于类,tree shake 无法删除死代码。例如,如果我从不使用

getUserData()
,它无论如何都会被导入,因为该方法是类的一部分。

我如何重写我的模块才能仅导入某些方法

import {init, getUserData} from "auth.js"

以及同时使用所有方法:

import auth from "auth.js"
javascript class webpack import es6-modules
1个回答
0
投票

JS 中的类是一种花哨的糖,但你不能将它与解构一起使用(因此,出于同样的原因,这些方法甚至不能被命名为导出)。

const person = new Human()

const { eat, drink } = person

// this would probably not work
eat()
drink()

原因是当你解构时你会失去上下文(

this
的值)。

因此,为了实现您所要求的目的,您需要从闭包中导出一堆函数

const state = {}

export function eat() {}
export function drink() {}

这两个函数都将使用

state
而不是
this
,模块本身充当闭包。

现在,对于导入,如果将其作为命名空间来处理,则可以两种方式使用它:

import { eat, drink } from './person'
import * as person from './person' // this is the "import namespace" pattern

// both work
eat()
person.eat()
© www.soinside.com 2019 - 2024. All rights reserved.