【问题标题】:Vue ElementUI Webpack externals using CDN使用 CDN 的 Vue ElementUI Webpack 外部
【发布时间】:2018-09-24 01:09:30
【问题描述】:

尝试使用 webpack4 使用 Vue 和 ElementUI 设置项目。我想从 CDN 中提取 Vue 和 ElementUI,所以我有下面的 webpack 配置

module.exports = {
  mode: "development",
  entry: ["./app.js"],
  externals: {
    vue: "Vue",
    "element-ui": "ElementUI"
  },
  module: {
    rules: [
      {
        test: /.vue$/,
        use: "vue-loader"
      },
      {
        test: /.css$/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /.ttf$|.woff$/,
        use: [{ loader: "url-loader", options: { limit: 10000 } }]
      }
    ]
  }
};

我的html文件

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <title>Document</title>
  <style>
    [v-cloak] {
      display: none;
    }
  </style>
</head>

<body>
  <div v-cloak id="root">
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.runtime.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/element-ui/2.3.4/index.js"></script>
  <script src="./dist/main.js"></script>
</body>

</html>

我的 app.js 有根 Vue 实例

import Vue from "vue";
import ElementUI from "element-ui";
import Counter from "./Counter.vue";

Vue.use(ElementUI);

var app = new Vue({
  el: "#root",
  render: h => h(Counter)
});

计数器组件在下面

<script>
export default {
  data() {
    return {
      counter: 0
    };
  },
  methods: {
    incement() {
      this.counter++;
    }
  }
};
</script>

<template>
  <div>
    <p><span>Count: </span>{{counter}}</p>
    <el-button @click="incement">Incement</el-button>
  </div>
</template>

当我在浏览器中打开应用程序时,出现以下错误

external_"ElementUI":1 Uncaught ReferenceError: ElementUI is not defined 在 webpack 的这一行生成 js 文件 module.exports = ElementUI;

这有什么我遗漏的吗? Vue 外部工作没有任何问题,只有元素 UI 有问题

【问题讨论】:

  • 您解决了这个问题吗?如果是,请发表答案

标签: webpack vue.js element-ui webpack-externals


【解决方案1】:

你的 webpack 配置 "element-ui": "ElementUI" 告诉 webpack “element-ui”可以作为全局变量 ElementUI

Webpack 创建代码 sn-p module.exports = ElementUI; 以便无论何时导入(或需要 w/e)“element-ui”,它都会返回这个全局变量。

现在看来 ElementUI 在全局范围内不存在,因此出现 ReferenceError。
脚本 ...element-ui/2.3.4/index.js 添加了一个全局变量 Element 所以尝试使用 "element-ui": "Element" 更改您的 webpack 配置

【讨论】:

  • 谢谢。您确实为 Stackoverflow 添加了一些有价值的东西。您的答案的一个补充; ElementUI 也需要在 app.js 中出现的任何地方变为 ELEMENT。 @PKool——你应该把它标记为你问题的正确答案。
  • 谢谢,我已经从这里开始了。但它看起来可行。
猜你喜欢
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 2018-09-05
  • 2018-11-11
  • 2019-05-08
  • 2018-05-30
  • 1970-01-01
  • 2020-02-22
相关资源
最近更新 更多