简体   繁体   中英

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 {} . It solves all of my issues with typescript but causes webpack to namespace everything on an object instead.

I'm having webpack generate umd and am testing the include via requirejs.

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:

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

.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.

// 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:

// 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
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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