简体   繁体   中英

Exclude Dependency from Webpack from create-react-app project

I have the following dependencies for my project.

"dependencies": {
    "amazon-cognito-identity-js": "^1.28.0",
    "bootstrap": "^3.3.7",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-bootstrap": "^0.31.5",
    "react-dom": "^16.2.0",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.0.17"
  },

I created my project using the nice boilerplate command, create-react-app my-app .

I'm now having an issue where I need to tell WebPack (which I found out React uses) to exclude the dependency of jQuery so I can get React Slider working.

Problem is the webpack config is part of the node modules. If I modify anything in there it won't reflect for any users downloading my project. There should be a way to override the default webpack settings but I'm not sure how to do this?

I found this project which might do what I need but not sure.

The instructions say I need to add this to the webpack config.

resolve: {
    alias: {
         "jquery": path.join(__dirname, "./jquery-stub.js");
    }
}

How do I do this given I don't have access to Webpack directly?

There is a module called react-app-rewired<\/a> that helps to extend the webpack config that comes with create react app without ejecting. An example of how you might add the resolve section looks like this

/* config-overrides.js */
let path = require('path')


function rewireJquery(config, env) {
  config.resolve = {
    alias: {
         "jquery": path.join(__dirname, "./jquery-stub.js");
    }
  };
  return config;
}
module.exports = function override(config, env) {
  //do stuff with the webpack config...
  // config = rewirePreact(config, env);
  if (env === "production") {
    config = rewireJquery(config, env);
  }
  return config;
};

@gbozee's answer worked for me with a small change in the rewireJquery function

/* config-overrides.js */
let path = require('path')


function rewireJquery(config, env) {
  config.resolve = config.resolve || {};
  config.resolve.alias = config.resolve.alias || {};
  config.resolve.alias.jquery = path.join(__dirname, "./stubs/jquery-stub.js");
  return config;
}
module.exports = function override(config, env) {
  //do stuff with the webpack config...
  // config = rewirePreact(config, env);
  if (env === "production") {
    config = rewireJquery(config, env);
  }
  return config;
};

You also need to remove the env === "production" condition for this to work on local.

Please note, entire credit goes to @gbozee's answer .

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