Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent TypeScript from interrupting Webpack building on unresolved variables declared on Webpack's ProvidePlugin?

Is there a way to prevent WebPack's building process from failing after typescript compiler start yelling on unresolved variables that actually are already configured on webpack's ProvidePlugin configuration?

webpack.config.js

plugins: [
...
new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "_": "underscore",
            "underscore": "underscore"
            //'process.env.NODE_ENV': '"development"'
        }),

]

tsconfig.json

{
  "compilerOptions": {


    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true,
    "declaration": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

https://webpack.github.io/docs/list-of-plugins.html#provideplugin

From my experience, the typescript is not aware of which variables will be injected into the module and as result the build is not completed.

This is the output of the build

ERROR in ./src/file1.component.ts
(77,9): error TS2304: Cannot find name '$'.

ERROR in ./src/file2.component.ts
(78,13): error TS2304: Cannot find name '$'.

ERROR in ./src/file3.ts
(155,15): error TS2304: Cannot find name 'jQuery'.

ERROR in ./src/file4.ts
(108,9): error TS2304: Cannot find name '$'.
like image 478
Lothre1 Avatar asked Jun 22 '16 16:06

Lothre1


1 Answers

I'm not fully satisfied with ahz's answer as I don't like to install typings globally or declare jQuery as any loosing all typechecking.

The solution that worked for me is to create global.d.ts with following content:

import * as _jQuery from 'jquery';

declare global {
  const jQuery: typeof _jQuery;
  const $: typeof _jQuery;
}

After that tsc passes without any warnings like Cannot find name '$'..

Found here.

like image 163
vitalets Avatar answered Dec 24 '22 23:12

vitalets