Typescript Webpack模块解析仅在运行时失败

时间:2017-05-28 18:42:21

标签: javascript typescript webpack

我试图在现有的Typescript项目上从grunt迁移到Webpack。即使我没有使用正确的import语句来导入依赖项,webpack构建也会成功。

tsconfig.json

{
    "compilerOptions": {
        "target": "ES5",
        "sourceMap": true,
        "module": "commonjs",
        "allowJs": true
    },
    "files": [
        "client/Index.ts"
    ],
    "exclude": [
        "node_modules"
    ],
    "types": []
}

webpack.config.js

const path = require('path');

module.exports = {
    entry: './client/Index.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, 'public', 'js')
    }
}

client/Index.ts

//import * as $ from "jquery";
$(() => {
    $(".title").html("Jquery works");
});

relevant dependencies from package.json

...
  "dependencies": {
    "@types/jquery": "^2.0.45",
    "jquery": "^3.2.1",
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.3",
    "webpack": "^2.6.1"
}
...

即使将import语句注释掉,webpack构建也完成了 -  我猜是因为它能够隐式找到jQuery打字文件。在运行时,我收到错误Uncaught ReferenceError: $ is not defined。这是有道理的,因为webpack并没有捆绑./~/jquery/dist/jquery.js。如果我取消注释Index.ts中的导入,该模块捆绑应用运行正常。所以我的问题是,如果我还没有导入引用的模块,如何让Webpack在构建时失败?

谢谢!

1 个答案:

答案 0 :(得分:1)

Typescript编译器通过查看node_modules来使用其隐式类型解析,所以它编译虽然webpack不包含实际的js库,除非你使用import。可以通过设置compilerOptions.types: []来禁用此默认的Typescript行为。

发布的代码包含错误:tsconfig.json "types": []位置错误。空类型数组属于compilerOptions.types

{
    "compilerOptions": {
        "target": "ES5",
        "sourceMap": true,
        "module": "commonjs",
        "allowJs": true,
        "types": []
    },
    "files": [
        "index.ts"
    ],
    "exclude": [
        "node_modules/*"
    ]
}

使用此tsconfig,webpack按预期失败: ERROR in ./client/Index.ts (2,1): error TS2304: Cannot find name '$'.