When working on a project that involves Typescript and Webpack, I want to make sure that global libraries, such as jQuery, are treated as UMD globals.
Currently, if I do not include import * as $ from 'jQuery'
in a file where I am using $
, webpack builds successfully but the script fails during runtime. On the other hand, omitting import * as _ from 'lodash'
causes webpack to fail, as expected.
Take a look at 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 to enforce the import statements in all .ts files?