将ES6类与Webpack捆绑在一起.有没有办法提升扩展班级? [英] Bundling ES6 classes with Webpack. Is there a way to hoist extended classes?

查看:90
本文介绍了将ES6类与Webpack捆绑在一起.有没有办法提升扩展班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Webpack可以提升扩展类吗?

Can Webpack hoist extended classes?

我正在使用Webpack和Babel捆绑和翻译一堆类,每个类都来自一个单独的文件.

I am using Webpack and Babel to bundle and transpile a bunch of classes, each from a separate file.

我的Webpack入口文件是一个index.js文件,其中包含按名称排序的每个类的导入语句,

My Webpack entry file is an index.js file containing import statements of every class ordered by name,

index.js:

import classA from './a';
import classB from './b';
import classC from './c';
import classD from './d';
...

a.js:

export class classA extends classD {
    constructor(...) {
        super(...);
    }
}

我的问题是,类是按名称顺序导入的,因此classD将在classA之后声明,并且会由于javascript提升/初始化规则而中断程序.

My problem is that the classes gets imported ordered by name, so classD will be declared after classA and will break the program because of javascript hoisting/initialization rules.

所以我的问题是Webpack是否可以对类进行排序并按必要的顺序排列它们?还是我手动选择它们的唯一选择?

So my question is if there is a way for Webpack to sort the classes and put them in the necessary order? Or is my only choice to sort them manually?

推荐答案

Webpack不会简单地将所有导入放到一个文件中,而是将它们作为模块保存.每个模块/文件都需要导入其依赖的所有内容,因此,只要您在Node中运行该模块即可(如果需要,在编译之后),它将可以正常工作.您的a.js不能单独工作,因为未定义classD.正确的方法是将其导入a.js:

Webpack does not simply put all the imports together into one file, but it keeps them as modules. Every module/file needs to import everything it depends on, so it would work if you just run that module in Node (after transpiling if necessary). Your a.js does not work by itself because classD is not defined. The correct way is to import it in a.js:

import ClassD from './d';

export default class ClassA extends ClassD {
  constructor(...) {
    super(...);
  }
}

import x from './file'将默认导出导入为x,因此您想在类中使用export default.

import x from './file' imports the default export as x, so you want to use export default for your classes.

您可能会担心从多个位置导入文件会多次包含该文件,但事实并非如此,它一次包含一次,并且该模块的每次导入都将在捆绑包中引用相同的文件.

You might be worried that importing a file from multiple places will include it multiple times, but that is not the case, it's included once and every import of that module will refer to the same one in the bundle.

注意:JavaScript中的约定是将 PascalCase 用于类.

Note: The convention in JavaScript is to use PascalCase for classes.

这篇关于将ES6类与Webpack捆绑在一起.有没有办法提升扩展班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆