【发布时间】:2019-10-28 13:14:57
【问题描述】:
我正在尝试使用official tutorial 在我的项目中使用 Typescript 设置 webpack。这是我的文件夹结构和重要文件:
├── dist
│ ├── bundle.js
│ └── index.html
├── package-lock.json
├── package.json
├── src
│ └── index.ts
├── tsconfig.json
└── webpack.config.js
src/index.ts:
// import _ from 'lodash';
const result = _.add(5, 6);
console.log(result);
webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"strict": true,
"module": "es6",
"target": "es5",
"allowSyntheticDefaultImports": true
}
}
请注意,在 index.ts 中,lodash 的导入(我运行 npm i lodash @types/lodash)被注释掉了。这应该是 TS 错误,但这是我在 VSCode 中看到的:
此外,我可以通过运行npx webpack 将项目编译成一个包(tsc src/index.ts 也可以)。但是,当我在浏览器中打开文件时,我会在控制台中看到:
很明显,这表明 TS 假定 _ 是全局定义的(不确定如何),即使包本身并未实际导入。取消注释导入修复了 ReferenceError,但我不明白为什么 Typescript Compiler 没有意识到 lodash 没有导入并报告编译错误。
不过,我确实注意到的一件事是,当我将文件更改为以下内容时,我收到此警告,并在 _.add 的下划线下方显示一条波浪形的红线:
// import _ from 'lodash';
import a from 'lodash';
const result = _.add(5, 6);
console.log(result);
'_' 指的是一个 UMD 全局,但当前文件是一个模块。考虑改为添加导入。 ts(2686)
【问题讨论】:
标签: typescript webpack types compiler-errors