Webpack + Typescript - How do I isolate an imported non-UMD module to one file?

Viewed 1015

In a project using Typescript and Webpack, I'd like to enforce that normally global libraries (e.g. jQuery) are treated as UMD globals.

Right now, if I omit import * as $ from 'jQuery' in a file where I reference $, webpack succeeds but the script fails at runtime. However, import * as _ from 'lodash' has the expected behavior by failing the webpack build when omitted.

Consider the following files:

first.ts

import * as $ from "jquery";
import * as _ from "lodash";

import { second } from "./second";

$(() => {
    const message = _.identity("first.ts");
    $(".first").html(message);
    second.Test();
});

second.ts

//import * as $ from "jquery";
//import * as _ from "lodash";

export const second = {
    Test: () => {
        const message = _.identity("second.ts");
        $(".second").html(message);
    }
}

index.html

<html>
    <head>
        <script type="text/javascript" src="./bundle.js">
        </script>
    </head>
<body>
<div class="first"></div>
<div class="second"></div>
</body>
</html>

package.json

{
  "name": "webpack-typescript-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/jquery": "^2.0.46",
    "@types/lodash": "^4.14.65",
    "jquery": "^3.2.1",
    "lodash": "^4.17.4",
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.3",
    "webpack": "^2.6.1"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "target": "ES5",
        "sourceMap": true,
        "module": "commonjs",
        "types": []
    },
    "include": [
        "./*.ts"
    ],
    "exclude": [
        "./node_modules"
    ]
}

webpack.config.js

const path = require('path');

module.exports = {
    entry: './first.ts',
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js']
    },
    module: {
        loaders: [
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname)
    }
}

Is there a way that I can enforce the import statements in all .ts files?

1 Answers
Related