PrinceG
PrinceG

Reputation: 982

How to create a separate file per module in Angular2 + Webpack?

I followed the steps in https://angular.io/docs/ts/latest/guide/webpack.html and was able to get it working.

But what I want is to have a separate file per module.

I tried adding a new entry point in webpack.common.js for each module but it returns an error when building the app.

module.exports = {
    entry: {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'app': './src/main.ts',
        'test': './src/app/test/test.module.ts'
    }
    .....
}

Is there a way to achieve this?

Upvotes: 1

Views: 707

Answers (2)

Thaadikkaaran
Thaadikkaaran

Reputation: 5226

You can use webpack's code-splitting with angular2's loadChildren method available in the route config. something like,

{
    path: 'yourroute', loadChildren: () => require.ensure('./yourmodule', (comp: any) => {
      return comp.default;
    }),
    ....
    ...
}

Here, the yourmodule would be loaded on-demand when the yourroute route is requested.

Upvotes: 2

Edwin Kato
Edwin Kato

Reputation: 553

To use multiple entry points you can pass an object to the entry option. Each value is treated as an entry point and the key represents the name of the entry point.

When using multiple entry points you must override the default output.filename option. Otherwise each entry point would write to the same output file. Use [name] to get the name of the entry point.

eg

entry: {
    polyfills: './src/polyfills.ts',
    vendor: './src/vendor.ts',
    app: './src/main.ts',
    test: './src/app/test/test.module.ts'
}
output: {
    path: path.join(__dirname, "dist"),
    filename: "[name].entry.js"
}

Try that without the quotes on the Left hand side. Also take note of the output

For more information please refer to Webpack multiple entry points

Upvotes: 0

Related Questions