简体   繁体   English

Webpack名称空间ES6模块

[英]Webpack namespacing es6 modules

Due to compatibility issues with typescript, babel, and webpack I have to use the export class Test {} syntax rather than export default class Test {} . 由于打字稿,babel和webpack的兼容性问题,我不得不使用export class Test {}语法,而不是export default class Test {} It solves all of my issues with typescript but causes webpack to namespace everything on an object instead. 它解决了我所有与打字稿有关的问题,但使webpack改为对对象上的所有内容进行命名空间。

I'm having webpack generate umd and am testing the include via requirejs. 我正在让webpack生成umd,并正在通过requirejs测试include。

However, rather than passing in the function directly I'm now getting an object with a property instead. 但是,不是直接传递函数,而是获取具有属性的对象。 This won't fly in my real app. 这不会在我的真实应用中显示。

{
    Test: function Test() {}
}

webpack.config.js: webpack.config.js:

module.exports = {
    entry: './test.js',
    output: {
        filename: 'a.js',
        libraryTarget: 'umd'
    },
    module: {
        loaders: [{
            test: /\.js$/, loader: 'babel-loader'
        }]
    }
};

.babelrc: .babelrc:

{
    "presets": ["es2015"]
}

I'm not sure if I've understood correctly, but after much experimentation I found the cleanest way to use modules in TypeScript is to simply use ES6 syntax in my source files. 我不确定我是否理解正确,但是经过大量实验,我发现在TypeScript中使用模块的最简单方法是在源文件中简单地使用ES6语法。

// src/foo/Foo.ts
export class Foo {}

// src/bar/Bar.ts
import {Foo} from '../foo/Foo';
export class Bar extends Foo {}

This way your source files can remain agnostic to your output module format. 这样,您的源文件就可以与输出模块格式无关。

For large libraries, it's possible to keep an index.ts at the root of each of your "namespaces", which will afford you greater flexibility when exporting modules: 对于大型库,可以将index.ts保留在每个“命名空间”的根目录下,这将在导出模块时为您提供更大的灵活性:

// src/widgets/FooWidget.ts
export class FooWidget {}

// src/widgets/BarWidget.ts
export class BarWidget {}

// src/widgets/index.ts
export * from './FooWidget';
export * from './BarWidget';

// src/index.ts
import * as widgets from './widgets';
import * as badgers from './badgers';
export {
  widgets,
  badgers
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM