2017-05-28 100 views
0

我正嘗試從grunt遷移到現有Typescript項目上的Webpack。即使我無法使用正確的import語句導入依賴關係,webpack構建也會成功。Typescript 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在構建時失敗?

謝謝!

回答

0

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 '$'.

相關問題