webpack - 使用 CDN 的 Vue ElementUI Webpack 外部

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

尝试使用 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 未捕获的 ReferenceError: ElementUI 未定义 在 webpack 中的这一行生成的 js 文件 module.exports = ElementUI;

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

最佳答案

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

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

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

关于webpack - 使用 CDN 的 Vue ElementUI Webpack 外部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49820973/

相关文章:

vue.js - 在 Vue Js 中的元素中添加行

vuejs2 - VueJs + 元素用户界面 : How to custom el-dialog title?

javascript - 如何导出/导入es6 js库

html - Vuetify 工具栏和居中 block 使页面可滚动

javascript - Webpack 无法导入从 git 安装的包

javascript - 引导下拉菜单上的 Vue 选择样式功能

javascript - 当父组件更新 vuejs 时,子组件不会更新

vuejs2 - 如何在Vue3项目中添加element-ui(现在叫element-plus)?

javascript - 将 Webpack 用于后端应用程序会降低性能吗?

vue.js - 如何使用 Phaser 3 和 Webpack 正确加载图像和 spritesheet?