Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

javascript - How to include jQuery properly in angular cli 1.0.0-rc.0?

I use jQuery-based select2 component in my AngularJS project. I had similar issue as guys here: https://github.com/fronteed/icheck/issues/322, and solved it using advice from there. To be accurate, I received error TypeError: $(...).select2 is not a function when not using that advice.

i.e. I added next lines to configuration of Webpack in @angular/cli/models/webpack-configs/common.js.

plugins: [
  new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    })
]

Is it the best possible way to enable jQuery in angular/cli?

I don't think that doing same as in https://github.com/angular/angular-cli/wiki/stories-global-lib is correct way, because

a) webpack bundles jQuery without need to specify it in scripts

b) it still throws TypeError: $(...).select2 is not a function error when you include it as described in story.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

i use jQuery in my project as follows.

  1. Install jQuery

    npm install --save jquery
    
  2. Install jQuery type defination for type checking.

    npm install --save-dev @types/jquery
    
  3. Add refenece of jquery file in "scripts" array inside angular-cli.json file.

    "scripts": [
        "../node_modules/jquery/dist/jquery.min.js"
     ]
    
  4. import jquery in any component you want to use.

    import * as jQuery from 'jquery';
    

that's it. the same way you can also use other libraries like moment.js , d3.js etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...