Tuesday, 4 April 2017

Webpack bundling custom Utilities separately from App code

I would like to bundle up my TypeScript ReactJs project using webpack. As my project is rather large, I want to bundle the utils separately from the main App code, so I can keep them separate.

I have the following folder structure;

Scripts
    - App
        - Components
            - ComponentOne.tsx
        - App.tsx
    - Utilities
        - Interfaces
            - IHelperInterface.ts
        - Interfaces.ts

ComponentOne imports IHelperInterface with a an import statement import { IHelperInterface } from '../../Utilities/Interfaces/IHelperInterface';

Along with my custom Utils, I am also using npm for various packages.

So my current webpack config looks like this;

var webpack = require('webpack'),
    pkg = require('./package.json');

module.exports = {
    entry: {
        app: './scripts/app/app',
        vendor: Object.keys(pkg.dependencies)
    },

    output: {
        filename: '[name].bundle.js',
        path: __dirname + '/wwwroot/js/app'
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' })
    ],

    // Enable sourcemaps for debugging webpack's output.
    devtool: 'source-map',

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: ['.ts', '.tsx', '.js', '.json']
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: 'awesome-typescript-loader' },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }
        ]
    }
};

My vendor files (npm packages) are being bundled together, and currently the rest is then bundled into 1 file. How can I modify the config to bundle my Utils?

I tried adding a 2nd entry point;

entry: {
    app: './scripts/app/app',
    utils: './scripts/interfaces/interfaces',
    vendor: Object.keys(pkg.dependencies)
},

In the hope that this would work, however it created utils.bundle.js file, but the app.bundle.js file still had all the code in it.



via Tim B James

No comments:

Post a Comment