Vue ElementUI Webpack externals using CDN

3.1k views Asked by At

Try to set up project with Vue and ElementUI using webpack4. I want to pull both Vue and ElementUI from CDN so I have below webpack config

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 } }]
      }
    ]
  }
};

my html file

<!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/[email protected]/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>

my app.js has has root Vue instance

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)
});

Counter component is below

<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>

When i open the app in the browser I get below error

external_"ElementUI":1 Uncaught ReferenceError: ElementUI is not defined at this line in webpack generated js file module.exports = ElementUI;

is there something I am missing in this? Vue external works without any issues only having problems with the element UI

1

There are 1 answers

2
Julien LB On BEST ANSWER

Your webpack configuration "element-ui": "ElementUI" tells webpack that "element-ui" is available as a global variable ElementUI.

Webpack creates the code snippet module.exports = ElementUI; so that whenever you import (or require w/e) "element-ui", it will return this global variable.

Now it seems that ElementUI does not exist in the global scope hence the ReferenceError.
The script ...element-ui/2.3.4/index.js adds a global variable Element so try to change your webpack configuration with "element-ui": "Element"