简体   繁体   中英

How to make Vue import files from assets folder instead of hardcoded script tags inside of index.html

I have a very simple structure and want to import assets that come from cdnjs.com.

Basically, those assets required for some third-party libraries, but the issue is it doesn't want to import them when I download and put all of the files inside of src/assets/lib and import them like

main.js:

import './assets/lib/jquery.min.js'

My application stops working and says that jQuery is not defined, but when I import them inside of index.html everything is fine:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.3.0/raphael.min.js"></script>

Detailed stack of error:

Uncaught ReferenceError: jQuery is not defined
    at eval (amalia.js.min.js?c1e6:27)
    at Object../src/assets/amalia/build/js/amalia.js.min.js (app.js:1362)
    at __webpack_require__ (app.js:849)
    at fn (app.js:151)
    at eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Videoplayer/AmaliaPlayer.vue?vue&type=script&lang=js&:2)
    at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Videoplayer/AmaliaPlayer.vue?vue&type=script&lang=js& (app.js:1010)
    at __webpack_require__ (app.js:849)
    at fn (app.js:151)
    at eval (AmaliaPlayer.vue?6fc3:1)
    at Module../src/components/Videoplayer/AmaliaPlayer.vue?vue&type=script&lang=js& (app.js:1688)

I need those assets located in src/assets folder because I want to build an SFC for further import in my projects

I also tried to set window.jQuery but seems like it's not the best approach so really want your help guys:)

After 2 hours of fighting I found the solution:

npm i jquery --save

// vue.config.js

const webpack = require('webpack')
module.exports = {
  configureWebpack: {
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery',
        jQuery: 'jquery'
      })
    ]
  },
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM