iT邦幫忙

0

html中,無法import axios

  • 分享至 

  • xImage

大家好,
之前我都是用框架,才沒發現這個問題。

今天才發現,如果是無框架的情況下,在自己寫的模組裡import axios,

//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!--<script  src="index.js"></script>-->
    <script type="module" src="./js/theAxios.js"></script>
</body>
</html>

import axios from 'axios'會有問題..

///theAxios.js
import axios from 'axios'

顯示的錯誤是:

Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../".

目前找到的解決方法,只有使用CDN..

如果我想用import的方式,該怎麼辦呢?
我還試了
(1)import axios from '../node_modules/axios'
顯示的錯誤是:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

(2)import axios from '../node_modules/axios/lib/core/Axios.js'
顯示的錯誤是:

Uncaught SyntaxError: The requested module '../node_modules/axios/lib/core/Axios.js' does not provide an export named 'default' (at theAxios.js:2:8)

感覺是Axios是用ES5的方式寫的?export的方式不一樣?

該怎麼import axios呢?感謝

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
淺水員
iT邦大師 6 級 ‧ 2022-05-20 08:44:30
最佳解答

axios 好像沒有給可以直接 import 的檔案
不過他的專案其實已經把設定檔(rollup.config.js)都寫好了
所以可以透過下列步驟拿到可用的 js

clone 專案後進入專案目錄

clone https://github.com/axios/axios.git
cd axios

安裝相關套件

npm install

使用 rollup 打包

npx rollup -c

以上步驟完成後,dist 資料夾會多出一個 esm 的資料夾
裡面的 js 檔就可以用 import 的方式使用了

greenriver iT邦研究生 5 級 ‧ 2022-05-20 14:48:36 檢舉

感謝~成功了

我要發表回答

立即登入回答