Search code examples
node.jstypescriptwebpacktsc

basic webpack typescript example fails on node_module include TS7016


Following the official webpack typescript integration guide https://webpack.js.org/guides/typescript/ and it is failing. What am I missing?

ERROR in /Users/kevzettler/code/hypeworks/src/index.ts
./src/index.ts
[tsl] ERROR in /Users/kevzettler/code/hypeworks/src/index.ts(1,21)
      TS7016: Could not find a declaration file for module 'lodash'. '/Users/kevzettler/code/hypeworks/node_modules/lodash/lodash.js' implicitly has an 'any' type.
ℹ 「wdm」: Failed to compile.

index.ts:

 import * as _ from 'lodash';

  function component() {
    const element = document.createElement('div');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    return element;
  }

document.body.appendChild(component());

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  devtool: 'inline-source-map',
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

package.json

{
  "name": "derp",
  "version": "0.0.1",
  "description": "",
  "private": true,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^8.0.4",
    "typescript": "^4.0.3",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12"
  },
  "dependencies": {
    "lodash": "^4.17.20",
    "uuid": "^8.3.1",
    "webpack-dev-server": "^3.11.0"
  }
}

Solution

  • You need to install the lodash types since they aren't available in the lodash package directly.

    npm install --save @types/lodash