【问题标题】:basic webpack typescript example fails on node_module include TS7016基本 webpack 打字稿示例在 node_module 上失败,包括 TS7016
【发布时间】:2020-10-08 17:32:16
【问题描述】:

按照官方 webpack typescript 集成指南https://webpack.js.org/guides/typescript/ 操作失败了。我错过了什么?

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"
  }
}

【问题讨论】:

  • lodash 有自己的声明文件吗?你试过npm install --save @types/lodash吗?
  • @dwosk 这就是我所缺少的。有什么办法可以自动化吗?
  • 这取决于包。有些原生支持 typescript,有些只能通过 @types/ 获得,就像 lodash 一样。它应该在库文档中。如果是后一种情况,则由您决定是否下载类型。
  • 您可以在添加其他包时使用typesync 定位和安装@types 包。

标签: node.js typescript webpack tsc


【解决方案1】:

您需要安装 lodash 类型,因为它们在 lodash 包中不直接可用。

npm install --save @types/lodash

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 2017-09-19
    • 2016-08-27
    • 2013-12-16
    • 2020-10-06
    • 2020-10-12
    • 1970-01-01
    • 2016-09-23
    • 2020-11-18
    相关资源
    最近更新 更多