0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Webpackで名前にハイフンを含むモジュールをimportする

Posted at

どうすればいいか

ケバブケースの名前をキャメルケースに書き換える。

例:
moment-duration-formatというモジュール名なら
import momentDurationFormat from 'moment-duration-format'

と書く。

何がしたかったのか

Webpackを使ってJavaScriptをクライアントサイドで実行している環境で、moment-duration-formatという、時間(期間)の表示を簡単にするライブラリ(Nodeモジュール)を導入したかった。

webpackを使っているので、ES Moduleスタイルで
import moment-duration-format from 'import-duration-format'と書いた。

どんな問題が起きたか

moment-duration-formatは時間を扱うライブラリであるmomentを拡張するライブラリであるためimport部は以下のようになるが

index.js
import moment 'import-duration-format'
import moment-duration-format from 'import-duration-format'

javascriptでは-が算術演算子として予約済みなせいか、momentが一つのシンボルとして認識されてしまう。

なぜかVSCodeの画面では import ... =' can only be used in a .ts file. というエラーメッセージとなっている。
EditableProgram_js_—_gachi-taite-designer-web.png

ブラウザ上のJavaScriptコンソールではModule parse failed: Identifier 'moment' has already been declared と上の行でmoment本体をimportしていることと関連したエラーメッセージとなっていた。
Developer_Tools_-_Vivaldi.png

なおmomentのimportをコメントアウトした場合のエラーメッセージとしては Module parse failed: Unexpected tokenとなり、import文の途中で算術演算子が登場することを怒られるようだ。
Developer_Tools_-_Vivaldi2.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?