npm下如何使用jQuery

  1. 安裝jQuery

    npm i jquery -S
    
  2. 配置webpack.config.js

    const path = require('path')
    const HtmlWebPackPlugin = require('html-webpack-plugin')
    // 第一步 引入webpack
    const webpack = require('webpack')
    const htmlWebPackPlugin = new HtmlWebPackPlugin({
        template: path.join(__dirname, './src/index.html'),
        filename: 'index.html'
    })
    
    module.exports = {
        mode: 'development',
        devtool: 'eval-source-map',
        plugins: [
            htmlWebPackPlugin,
            // 第二步 配置組件
            new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" })
        ],
        module: {
            rules: [
                { test: /\.js|jsx$/, use: 'babel-loader', exclude: /node_modules/ },
            ]
        }
    }
    
  3. 案例
    在用的地方使用import $ from 'jquery' 就可以正常使用了

    import React from 'react'
    import ReactDOM from 'react-dom'
    import $ from 'jquery'
    
    class UserGist extends React.Component {
      constructor(props) {
          super(props);
          this.state = {username: '', lastGistUrl: ''};
      }
     
     
      componentDidMount() {
        this.serverRequest = $.get(this.props.source, function (result) {
          var lastGist = result[0];
          this.setState({
            username: lastGist.owner.login,
            lastGistUrl: lastGist.html_url
          });
        }.bind(this));
      }
     
      componentWillUnmount() {
        this.serverRequest.abort();
      }
     
      render() {
        return (
          <div>
            {this.state.username} 
            <a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
          </div>
        );
      }
    }
     
    ReactDOM.render(
      <UserGist source="https://api.github.com/users/octocat/gists" />,
      document.getElementById('app')
    );
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章