
jQueryのimport時にエラー
webpackでjQueryをimportしようとすると以下のようなエラーが出ることがある。
import $ from 'jquery'
$(function() {
$('h1').css('background', 'red')
})
ERROR in index.ts(1,8) TS1259: Module '"/sample/node_modules/@types/jquery/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flag
直訳するとjQueryのモジュールは 'allowSyntheticDefaultImports' フラグを使ってのみデフォルトでインポートできると書かれている。
なので上記エラーはtsconfig.jsonにallowSyntheticDefaultImportsをtrueにしたものを追記すれば解消される。
{
"compilerOptions": {
"module": "esnext",
"target": "es6",
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
},
"files": [
"index.ts"
]
}
一応 import * as $ from 'jquery' に直すことでも読み込めるが、特に理由がなければallowSyntheticDefaultImports: trueの設定で対応したほうが良い。