Javascript 如何在没有 NPM 或 Webpack 的情况下将 CDN 包含到 VueJS CLI?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49330055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:21:29  来源:igfitidea点击:

How to include a CDN to VueJS CLI without NPM or Webpack?

javascriptwebpackvue.jsdatatablescdn

提问by Fabricio Chacon

I'm new on VueJS ans Webpack. I've created a project with VueJS CLI and trying to work with it. I need to insert an CDN to my code.

我是 VueJS ans Webpack 的新手。我已经使用 VueJS CLI 创建了一个项目并尝试使用它。我需要在我的代码中插入一个 CDN。

When working with standard HTML, CSS & JS solutions, I'd include CDNs like this:

当使用标准的 HTML、CSS 和 JS 解决方案时,我会包含这样的 CDN:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>False Merge</title>

    <!-- CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.css"/>

    <!-- StyleSheets -->
    <link rel="stylesheet" href="public/stylesheets/index.css" />
</head>

<body>


    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>

    <script src="public/javascripts/index.js"></script>

</body>

</html>

As you can see, you can add a CDN script with the HTML script tag, and start using it in the JS.

如您所见,您可以添加带有 HTML script 标签的 CDN 脚本,并开始在 JS 中使用它。

I'm trying to do the same with VueJS in a component. I've got the template and style sections ready.

我正在尝试对组件中的 VueJS 做同样的事情。我已经准备好了模板和样式部分。

Unfortunately, I don't know how to add in a simple way a CDN to use inmediately in the script tag within the Vue component. I tried to do this but it is not working.

不幸的是,我不知道如何以简单的方式添加 CDN,以便在 Vue 组件的脚本标签中立即使用。我试图这样做,但它不起作用。

<template>
  <div class="index">
    <div class="container">
      <table id="table_dataset" class="display">
      </table>
    </div>
  </div>
  
</template>

<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>
<script>
  export default {
    name: 'Index',
    data() {
      return { 
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

Is there a way to add a CDN (without Webpack or NPM) to a VueJS component?

有没有办法向 VueJS 组件添加 CDN(没有 Webpack 或 NPM)?

回答by acdcjunior

Unfortunately, no, you can't add a <script>tag to a specific component via template.

不幸的是,不,您不能通过 template<script>向特定组件添加标签。

In your case you have some options:

在您的情况下,您有一些选择:

1: Use NPM

1:使用NPM

Propertly install the dependency using npm

使用正确安装依赖项 npm

  • Pros:proper usage of NPM and Webpack; scoped definition;
  • Cons:the script must be available as a NPM package.
  • Note: when available this is the recommendedapproach.
  • Steps:

  • 优点:正确使用 NPM 和 Webpack;范围定义;
  • 缺点:脚本必须作为 NPM 包提供。
  • 注意:如果可用,这是推荐的方法。
  • 脚步:



2: Add <script>tag to index.html

2:添加<script>标签 index.html

Locate and a dd the <script>tag to your index.html

找到<script>标签并将其添加到您的index.html

  • Pros:the <script>tag is clearly (and declaratively) added to the HTML source. The script will only be loaded once.
  • Cons:the script will be globally loaded.
  • Steps:
    • Just add the <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>to the end of the index.htmlfile, preferably right before </body>.
  • 优点:<script>标签是清楚地(和声明)添加到HTML源。脚本只会加载一次。
  • 缺点:脚本将被全局加载。
  • 脚步:
    • 只需将<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>加到index.html文件末尾,最好在</body>.


3: Create the <script>tag programatically

3:以<script>编程方式创建标签

The other alternative is to create the scripttag programatically at the component, when the component is lodaded.

另一种选择是script在加载组件时以编程方式在组件上创建标记。

  • Pros:the code stays in the component only. Your external script will be loaded only when the component is loaded.
  • Cons:the script still will be globally available once it is loaded.
  • Steps/Code:

    <script>
      export default {
        name: 'Index',
        data() {
          return { 
          }
        },
        mounted() {
          if (document.getElementById('my-datatable')) return; // was already loaded
          var scriptTag = document.createElement("script");
          scriptTag.src = "https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js";
          scriptTag.id = "my-datatable";
          document.getElementsByTagName('head')[0].appendChild(scriptTag);
        }
      }
    </script>
    
  • 优点:代码仅保留在组件中。只有在加载组件时才会加载您的外部脚本。
  • 缺点:脚本加载后仍将全局可用。
  • 步骤/代码:

    <script>
      export default {
        name: 'Index',
        data() {
          return { 
          }
        },
        mounted() {
          if (document.getElementById('my-datatable')) return; // was already loaded
          var scriptTag = document.createElement("script");
          scriptTag.src = "https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js";
          scriptTag.id = "my-datatable";
          document.getElementsByTagName('head')[0].appendChild(scriptTag);
        }
      }
    </script>
    

回答by N8_

I don't know if this is still a concern, but you could also give vue-meta a look. I'm using it to create a better SEO implementation, but with it, you can include CSS, and/or JS files for specific components. You can even set the individual files to preload if you wanted. Here's a pretty good write-up. https://alligator.io/vuejs/vue-seo-tips/

我不知道这是否仍然是一个问题,但你也可以看看 vue-meta。我正在使用它来创建更好的 SEO 实现,但使用它,您可以包含特定组件的 CSS 和/或 JS 文件。如果需要,您甚至可以将单个文件设置为预加载。这是一篇很好的文章。https://alligator.io/vuejs/vue-seo-tips/

In there it says that vue-meta isn't stable, but the article was written in February of 2018, and the version as of today, is 2.2.1.

里面说 vue-meta 不稳定,但是文章写于 2018 年 2 月,今天的版本是 2.2.1。

  1. add this line to your package.json file within the dependencies object: "vue-meta": "^2.2.1",
  1. 将此行添加到依赖项对象中的 package.json 文件中: "vue-meta": "^2.2.1",

note - omit the trailing comma if it's to be the last line of the dependencies object

注意 - 如果要成为依赖项对象的最后一行,请省略结尾的逗号

  1. open a terminal and cd to the dir which contains above mentioned package.json file. (BTW, this is all super easy if you use the vue ui).
  2. in the terminal run: npm install
  1. 打开终端并 cd 到包含上述 package.json 文件的目录。(顺便说一句,如果您使用 vue ui,这一切都非常简单)。
  2. 在终端运行: npm install

Then add the following to your main.js file.

然后将以下内容添加到您的 main.js 文件中。

import Meta from "vue-meta";
Vue.use(Meta);

Now you can freely load static CSS/JS assets. This works for local, or from cdn. Below is my example. Disregard my imports, components and methods... they aren't related to vue-meta and may differ from yours. I just wanted to show you a working version.

现在您可以自由加载静态 CSS/JS 资产。这适用于本地或来自 cdn。下面是我的例子。忽略我的导入、组件和方法……它们与 vue-meta 无关,可能与您的不同。我只是想向您展示一个工作版本。

<script>
import { page } from "vue-analytics";
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
export default {
  components: {
    Header,
    Footer
  },
  data: function() {
    return {};
  },
  methods: {
    track() {
      page("/");
    }
  },
  metaInfo: {
    link: [
      {
        rel: "preload",
        as: "style",
        href: "https://cdn.jsdelivr.net/npm/[email protected]/dist/bootstrap-vue.min.css"
      },
      {
        rel: "preload",
        as: "style",
        href: "https://fonts.googleapis.com/css?family=Cinzel|Great+Vibes|Montserra"
      },
      {
        rel: "preload",
        as: "style",
        href: "/content/css/site.css"
      },
      {
        rel: "stylesheet",
        href:
          "https://fonts.googleapis.com/css?family=Cinzel|Great+Vibes|Montserra"
      },
      {
        rel: "stylesheet",
        href: "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css",
        integrity:
          "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
        crossorigin: 'anonymous"'
      },
      {
        rel: "stylesheet",
        href: "https://cdn.jsdelivr.net/npm/[email protected]/dist/bootstrap-vue.min.css",
        async: true,
        defer: true
      },
      {
        rel: "stylesheet",
        href: "https://use.fontawesome.com/releases/v5.8.1/css/all.css",
        integrity:
          "sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf",
        crossorigin: 'anonymous"',
        async: true,
        defer: true
      },
      {
        rel: "stylesheet",
        href: "/content/css/site.css",
        async: true,`enter code here`
        defer: true
      },
      { rel: 'favicon', href: 'favicon.ico' }
    ],
    script: [{ src: "https://unpkg.com/axios/dist/axios.min.js", async: true, defer: true }],
  }
};
</script>