Search code examples
typescriptwebpackwebpack-2

How to exclude from webpacked JS, a library that's required by the Typescript setup


Thanks for your guidance, am relatively new to in-depth Typescript. I'm a server-side fellow admittedly, but I like the cozy feeling Typescript provides! Feels close to home.

As test case, I'm trying to 'baby steps' a script into a primary project that already includes jQuery. This test case imports jQuery in its code.

import $ = require("jquery");

class TestCase {
    constructor(localeData) {
        $('body').css('background', 'blue');
    }
}

This compiles (with Typescript) into this expected format

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const $ = require("jquery");
class TestCase {
    constructor(localeData) {
        $('body').css('background', 'blue');
    }
}

Beyond this, I've executed these commands:

npm install -g webpack

npm install ts-loader --save

And have adde this webpack.config.js

module.exports = {
    entry: './testcase.ts',
    output: {
        filename: 'testcase.js'
    },
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.js']
    },
    module: {
        loaders: [
            {test: /\.ts$/, loader: 'ts-loader'}
        ]
    }
};

I thereafter run 'webpack' and get as expected, all of jQuery before my little test script. The caveat is that the project in which I want to insert this, already includes jQuery.

How do I handle this case; I imagine that I have to tell webpack to exclude this import somehow?

Thanks!


Solution

  • Well. Seems to be as simple as this?

    module.exports = {
        entry: './testcase.ts',
        output: {
            filename: 'testcase.js'
        },
        resolve: {
            extensions: ['.webpack.js', '.web.js', '.ts', '.js']
        },
        externals: {
            "jquery": "jQuery",
        },
        module: {
            loaders: [
                {test: /\.ts$/, loader: 'ts-loader'}
            ]
        }
    };