Vite 构建警告:如果没有 type="module" 属性,则无法捆绑脚本

doc*_*tus 12 javascript vite

<!-- index.html -->
<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>
<script type="module" src="./scripts/auth.js"></script>

Run Code Online (Sandbox Code Playgroud)
# Vite terminal after running "npm run build"
build started...
<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js">
in "/index.html" can't be bundled without type="module" attribute
Run Code Online (Sandbox Code Playgroud)

我正在尝试向我的脚本添加一些外部脚本,index.html但 Vite 构建过程假设我想要捆绑这些脚本。有什么办法可以抑制这个消息吗?

Sla*_*orx 5

有一个简单的答案,它实际上在日志本身中。

只需将该type="module"属性添加到您的脚本标签即可。

像这样: <script type="module" src="/src/main.js"></script>

希望能帮助到你。

  • 这是不正确的建议。如果您实际上尝试将脚本作为模块执行,通常它不会可靠地工作。例如,模块会在 javascript 严格模式下自动执行,而传统脚本则不会。这足以使许多脚本崩溃。 (7认同)

kl0*_*l02 1

我想我已经明白了,但一如既往的ymmv。

如果您需要全局的,您可以在 main.js 或 app.vue 中执行此操作,但我只需要一页上的外部脚本。老派的方法似乎可以做到这一点:

    mounted() {
      let externalScript = document.createElement('script');
      externalScript.setAttribute('src', 'https://[scripturletc].min.js')
      document.head.appendChild(externalScript)
    }
Run Code Online (Sandbox Code Playgroud)

注意:如果您以新的 vue3 方式处理组件,我认为上面的行将出现在您的设置块中。

  • 只需保留警告即可:)正在进行中的工作:https://github.com/vitejs/vite/pull/11138 (2认同)