react项目引入jquery文件,如何配置package.json和webpack.config.js,其他js文件怎么用?

图片描述

package.json

{
  "dependencies": {
    "babel-core": "^6.26.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "express": "^4.15.4",
    "html-webpack-plugin": "^2.30.1",
    "react-hot-loader": "^1.3.1",
    "webpack": "^3.6.0",
    "webpack-dev-middleware": "^1.12.0",
    "webpack-dev-server": "^2.8.2"
  },
  "name": "reactApp01",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "build": "webpack",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --hot --inline"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
var config  = {
    //此处指明路口文件位置
    entry: './main.js',   //设置入口文件
    //配置打包结果,
    //path配置定义了输出的文件位置
    //filename则定义了打包结果文件的名称
    devtool: 'inline-source-map',
    output: {//输出目录
        filename: 'bundle.js',//设置导出文件为index.js
        path: path.resolve(__dirname, 'dist')//打包后的js文件存放的地方
    },
    //设置本地服务器端口号为9001,此端口可以自己设定,但记住不能与其他服务端口重复
    devServer:{
        //contentBase: './dist',//tell the dev server where to look for files
        hot: true,
        inline:true,
        port:7700

    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ],
    //定义了对模块的处理逻辑,这里可以用loaders定义一系列的加载器,以及一些正则,
    //当需要加载的文件匹配test的正则时,会调用后面的loader对文件进行处理,
    //所以这就是webpack骚的可怕的地方。。。。。
    module:{
        loaders:[{
            test:/\.jsx?$/,
            exclude:/node_modules/,
            loader:'babel-loader',
            query:{
                presets:['es2015','react']
            }
        }]
    }
};

module.exports = config;
阅读 5.6k
4 个回答

你可以通过npm安装jquery,在你用的地方import就行了

import $ from 'jquery'

在webpack配置文件的

module:{
        rules:[
                {
                    test: require.resolve('jquery'),
                    use: [{
                        loader: 'expose-loader',
                        options: 'jQuery'
                    },{
                        loader: 'expose-loader',
                        options: '$'
                    }]
                }
            ]
        }

然后在要用的地方 import $ from 'expose-loader?$!jquery';

推荐问题
宣传栏