Giter Site home page Giter Site logo

react-app-rewired's Introduction

ℹ️ Before submitting an issue to this repo - Ensure it's a issue with the code in this repo, not a how do I configure something with Webpack question (post something on Stack Overflow or Spectrum). It's your config you "own" it.

npm version npm monthly downloads

react-app-rewired

Tweak the create-react-app webpack config(s) without using 'eject' and without creating a fork of the react-scripts.

All the benefits of create-react-app without the limitations of "no config". You can add plugins, loaders whatever you need.

Rewire Your App ☠

As of Create React App 2.0 this repo is "lightly" maintained mostly by the community at this point.

⚠️ Please Note:

By doing this you're breaking the "guarantees" that CRA provides. That is to say you now "own" the configs. No support will be provided. Proceed with caution.

"Stuff can break" — Dan Abramov https://twitter.com/dan_abramov/status/1045809734069170176


Note: I personally use next.js or Razzle which both support custom Webpack out of the box.

Alternatives

You can try customize-cra for a set of CRA 2.0 compatible rewirers, or any of the alternative projects and forks that aim to support 2.0:

How to rewire your create-react-app project

Create your app using create-react-app and then rewire it.

1) Install react-app-rewired

For create-react-app 2.x with Webpack 4:
npm install react-app-rewired --save-dev
For create-react-app 1.x or react-scripts-ts with Webpack 3:
npm install [email protected] --save-dev

2) Create a config-overrides.js file in the root directory

/* config-overrides.js */

module.exports = function override(config, env) {
  //do stuff with the webpack config...
  return config;
}
+-- your-project
|   +-- config-overrides.js
|   +-- node_modules
|   +-- package.json
|   +-- public
|   +-- README.md
|   +-- src

3) 'Flip' the existing calls to react-scripts in npm scripts for start, build and test

  /* package.json */

  "scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test",
+   "test": "react-app-rewired test",
    "eject": "react-scripts eject"
}

Note: Do NOT flip the call for the eject script. That gets run only once for a project, after which you are given full control over the webpack configuration making react-app-rewired no longer required. There are no configuration options to rewire for the eject script.

4) Start the Dev Server

npm start

5) Build your app

npm run build

Extended Configuration Options

You can set a custom path for config-overrides.js. If you (for instance) wanted to use a 3rd-party config-overrides.js that exists in node_modules, you could add the following to your package.json:

"config-overrides-path": "node_modules/some-preconfigured-rewire"

By default, the config-overrides.js file exports a single function to use when customising the webpack configuration for compiling your react app in development or production mode. It is possible to instead export an object from this file that contains up to three fields, each of which is a function. This alternative form allows you to also customise the configuration used for Jest (in testing), and for the Webpack Dev Server itself.

This example implementation is used to demonstrate using each of the object require functions. In the example, the functions:

  • have some tests run conditionally based on .env variables
  • set the https certificates to use for the Development Server, with the filenames specified in .env file variables.
module.exports = {
  // The Webpack config to use when compiling your react app for development or production.
  webpack: function(config, env) {
    // ...add your webpack config
    return config;
  },
  // The Jest config to use when running your jest tests - note that the normal rewires do not
  // work here.
  jest: function(config) {
    // ...add your jest config customisation...
    // Example: enable/disable some tests based on environment variables in the .env file.
    if (!config.testPathIgnorePatterns) {
      config.testPathIgnorePatterns = [];
    }
    if (!process.env.RUN_COMPONENT_TESTS) {
      config.testPathIgnorePatterns.push('<rootDir>/src/components/**/*.test.js');
    }
    if (!process.env.RUN_REDUCER_TESTS) {
      config.testPathIgnorePatterns.push('<rootDir>/src/reducers/**/*.test.js');
    }
    return config;
  },
  // The function to use to create a webpack dev server configuration when running the development
  // server with 'npm run start' or 'yarn start'.
  // Example: set the dev server to use a specific certificate in https.
  devServer: function(configFunction) {
    // Return the replacement function for create-react-app to use to generate the Webpack
    // Development Server config. "configFunction" is the function that would normally have
    // been used to generate the Webpack Development server config - you can use it to create
    // a starting configuration to then modify instead of having to create a config from scratch.
    return function(proxy, allowedHost) {
      // Create the default config by calling configFunction with the proxy/allowedHost parameters
      const config = configFunction(proxy, allowedHost);

      // Change the https certificate options to match your certificate, using the .env file to
      // set the file paths & passphrase.
      const fs = require('fs');
      config.https = {
        key: fs.readFileSync(process.env.REACT_HTTPS_KEY, 'utf8'),
        cert: fs.readFileSync(process.env.REACT_HTTPS_CERT, 'utf8'),
        ca: fs.readFileSync(process.env.REACT_HTTPS_CA, 'utf8'),
        passphrase: process.env.REACT_HTTPS_PASS
      };

      // Return your customised Webpack Development Server config.
      return config;
    };
  },
  // The paths config to use when compiling your react app for development or production.
  paths: function(paths, env) {
    // ...add your paths config
    return paths;
  },
}

1) Webpack configuration - Development & Production

The webpack field is used to provide the equivalent to the single-function exported from config-overrides.js. This is where all the usual rewires are used. It is not able to configure compilation in test mode because test mode does not get run through Webpack at all (it runs in Jest). It is also not able to be used to customise the Webpack Dev Server that is used to serve pages in development mode because create-react-app generates a separate Webpack configuration for use with the dev server using different functions and defaults.

2) Jest configuration - Testing

Webpack is not used for compiling your application in Test mode - Jest is used instead. This means that any rewires specified in your webpack config customisation function will not be applied to your project in test mode.

React-app-rewired automatically allows you to customise your Jest configuration in a jest section of your package.json file, including allowing you to set configuration fields that create-react-app would usually block you from being able to set. It also automatically sets up Jest to compile the project with Babel prior to running tests. Jest's configuration options are documented separately at the Jest website. Note: Configuration arrays and objects are merged, rather than overwritten. See #240 and #241 for details

If you want to add plugins and/or presets to the Babel configuration that Jest will use, you need to define those plugins/presets in either a babel section inside the package.json file or inside a .babelrc file. React-app-rewired alters the Jest configuration to use these definition files for specifying Babel options when Jest is compiling your react app. The format to use in the Babel section of package.json or the .babelrc file is documented separately at the Babel website.

The jest field in the module.exports object in config-overrides.js is used to specify a function that can be called to customise the Jest testing configuration in ways that are not possible in the jest section of the package.json file. For example, it will allow you to change some configuration options based on environment variables. This function is passed the default create-react-app Jest configuration as a parameter and is required to return the modified Jest configuration that you want to use. A lot of the time you'll be able to make the configuration changes needed simply by using a combination of the package.json file's jest section and a .babelrc file (or babel section in package.json) instead of needing to provide this jest function in config-overrides.js.

3) Webpack Dev Server

When running in development mode, create-react-app does not use the usual Webpack config for the Development Server (the one that serves the app pages). This means that you cannot use the normal webpack section of the config-overrides.js server to make changes to the Development Server settings as those changes won't be applied.

Instead of this, create-react-app expects to be able to call a function to generate the webpack dev server when needed. This function is provided with parameters for the proxy and allowedHost settings to be used in the webpack dev server (create-react-app retrieves the values for those parameters from your package.json file).

React-app-rewired provides the ability to override this function through use of the devServer field in the module.exports object in config-overrides.js. It provides the devServer function a single parameter containing the default create-react-app function that is normally used to generate the dev server config (it cannot provide a generated version of the configuration because react-scripts is calling the generation function directly). React-app-rewired needs to receive as a return value a replacement function for create-react-app to then use to generate the Development Server configuration (i.e. the return value should be a new function that takes the two parameters for proxy and allowedHost and itself returns a Webpack Development Server configuration). The original react-scripts function is passed into the config-overrides.js devServer function so that you are able to easily call this yourself to generate your initial devServer configuration based on what the defaults used by create-react-app are.

4) Paths configuration - Development & Production

The paths field is used to provide overrides for the create-react-app paths passed into webpack and jest.

5) Provide rewired webpack config for 3rd party tools

Some third party tools, like react-cosmos relies on your webpack config. You can create webpack.config.js file and export rewired config using following snippet:

const { paths } = require('react-app-rewired');
// require normalized overrides
const overrides = require('react-app-rewired/config-overrides');
const config = require(paths.scriptVersion + '/config/webpack.config.dev');

module.exports = overrides.webpack(config, process.env.NODE_ENV);

Then just point to this file in tool configuration.

Additional Issues and Options

1) Entry Point: 'src/index.js'

At this point in time, it is difficult to change the entry point from the default src/index.js file due to the way that file is included by create-react-app. The normal rewiring process gets bypassed by several of the create-react-app scripts.

There are three work-arounds available here:

  1. Simply require/import your desired file from inside the src/index.js file, like:
require('./index.tsx');
  1. Use a customised version of the react-scripts package that changes the entry point inside the scripts themselves (e.g. react-scripts-ts for a typescript project - see below for how to use custom script versions with react-app-rewired).
  2. Override the react-dev-utils/checkRequiredFiles function to always return true (causing create-react-app to no longer try to enforce that the entry file must exist).

2) Custom scripts versions

It is possible to use a custom version of the react-scripts package with react-app-rewired by specifying the name of the scripts package in the command line option --scripts-version or setting REACT_SCRIPTS_VERSION=<...> via the environment.

A working example for using the scripts version option is:

{
  "scripts": {
    "start": "react-app-rewired start --scripts-version react-scripts-ts",
    "build": "react-app-rewired build --scripts-version react-scripts-ts",
    "test": "react-app-rewired test --scripts-version react-scripts-ts",
    "eject": "react-scripts eject"
  }
}
React-app-rewired 2.x requires a custom react-scripts package to provide the following files:
  • config/env.js
  • config/webpack.config.js
  • config/webpackDevServer.config.js
  • scripts/build.js
  • scripts/start.js
  • scripts/test.js
  • scripts/utils/createJestConfig.js
React-app-rewired 1.x requires a custom react-scripts package to provide the following files:
  • config/env.js
  • config/webpack.config.dev.js
  • config/webpack.config.prod.js
  • config/webpackDevServer.config.js
  • scripts/build.js
  • scripts/start.js
  • scripts/test.js
  • scripts/utils/createJestConfig.js

3) Specify config-overrides as a directory

React-app-rewired imports your config-overrides.js file without the '.js' extension. This means that you have the option of creating a directory called config-overrides at the root of your project and exporting your overrides from the default index.js file inside that directory.

If you have several custom overrides using a directory allows you to be able to put each override in a separate file. An example template that demonstrates this can be found in Guria/rewired-ts-boilerplate at Github.

4) Specify config-overrides location from command line

If you need to change the location of your config-overrides.js you can pass a command line option --config-overrides to the react-app-rewired script.

Version 1.X Community Maintained Rewires (Check the plugin repo for 2.0 support)

Babel plugins

Webpack plugins

Loaders

Other

Development

When developing this project, ensure you have yarn installed.

Quick Start

To run the test app, navigate to the directory and run:

yarn setup
yarn start

(when you are finished, run yarn teardown to clean up)

Commands

Here is a list of all the available commands to help you in development

  • yarn setup - installs dependences and links test/react-app
  • yarn start - starts the react app
  • yarn build - builds the react app
  • yarn test - tests the react app
  • yarn teardown - unlinks test/react-app and removes dependencies

Why This Project Exists

See: Create React App — But I don’t wanna Eject.

react-app-rewired's People

Contributors

afc163 avatar andriijas avatar aze3ma avatar bencergazda avatar chrbala avatar dawnmist avatar dependabot[bot] avatar detrohutt avatar donniewest avatar fezvrasta avatar fupengl avatar guria avatar harrysolovay avatar hassanbazzi avatar hurtak avatar icopp avatar leifdejong avatar likun7981 avatar lnhrdt avatar luftywiranda13 avatar marcopeg avatar nicholasc avatar oklas avatar osdevisnot avatar pasviegas avatar poozhu avatar raodurgesh avatar satazor avatar tiffon avatar timarney avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-app-rewired's Issues

Commons chunk plugin

Hi, how can achieve use CommonsChunkPlugin? I have try that with no success:

config-overrides.js:

module.exports = function override(config, env) {


const webpack = require('webpack');

const { CommonsChunkPlugin } = webpack.optimize;

  var commonsChunkPluginCommon = new CommonsChunkPlugin({
    children: true,
    async: 'common',
    minChunks: 2,
  });
  var commonsChunkPluginVendor =  new CommonsChunkPlugin({
    children: true,
    async: 'vendor',
    minChunks: function(module) {
      // this assumes your vendor imports exist in the node_modules directory
      return module.context && module.context.indexOf('node_modules') !== -1;
    },
  });

  config.plugins.push(commonsChunkPluginCommon);
  config.plugins.push(commonsChunkPluginVendor);
  return config;
}

Thanks!

build.js not respecting NODE_PATH

in scripts/build.js

const webpackConfig = paths.scriptVersionDir + '/config/webpack.config.prod';

paths.scriptVersionDir assumes that node_modules is in that directory which breaks everything. :(

This should respect NODE_PATH just like everything else.

provide a way to extend babelTransform for jest

I need a way to extend babelTransform.js for jest other then .babelrc because I have to make js require statements to create config for babel plugin.

I tried to use .babelrc.js, but seems it will be supported only by babel@7 which still in alpha/beta state.

TypeError: Path must be a string. Received -1

Configured by following README.md, met error:

 yarn start
yarn start v0.19.1
$ react-app-rewired start
/Users/lijie/test -1
path.js:7
    throw new TypeError('Path must be a string. Received ' + inspect(path));
    ^

TypeError: Path must be a string. Received -1
    at assertPath (path.js:7:11)
    at Object.join (path.js:1211:7)
    at Object.<anonymous> (/Users/lijie/test/node_modules/react-app-rewired/config/paths.js:27:31)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)

See https://github.com/timarney/react-app-rewired/blob/master/packages/react-app-rewired/config/paths.js#L17-L26, seems custom_scripts always -1, and then
const scriptVersion = custom_scripts || 'react-scripts' also -1.

My environment:
Node.js 7.4.0
react-scripts 0.9.0
react-app-rewired 0.6.4

MobX rewire

Plugin tries to resolve from src dir not react-app-rewire-mobx dir.

Error in ./src/index.js
Module build failed: ReferenceError: Unknown plugin "transform-decorators-legacy" specified in "base" at 0, attempted to resolve relative to "/mydir/src"
    at Array.map (native)
 @ multi main

@pasviegas any chance you could shed some light on this was thinking this would work like your relay rewire

CRA 0.10.0 - prep

@pasviegas @Hurtak just FYI

CRA - pushed up a canary version to NPM so you can now test rewires against the 0.10.0 (webpack2 version of that repo)

I setup a Webpack2 branch of this repo and also pushed up alphas.

I have this repo running to test the MobX rewire - https://github.com/timarney/mobx-rewire-test with CI.

==============================

npm info react-scripts

npm info react-app-rewired
{ name: 'react-scripts',
 ...
     canary: '0.10.0-alpha.328cb32e' },

MobX rewire config not picked up by Jest

Thanks for the create project!

I noticed that the MobX rewiring worked great for running the app. But running the tests breaks as soon as decorators are used. It seems the babelrc config used by webpack is not picked up by jest. Is this something that could be addressed?

Thanks!

Jest failing on Imports

Hi,
Sorry if this is related to the other open issues related to Jest, but we are running into an issue and are not sure if it's caused by a misconfiguration on our side or if it's a known issue. If it is related to the other ones, let me know and I can close this and move it there.

We using react-app-rewired for decorator support with Mobx (react-app-rewire-mobx 1.0.3). We are on the latest version of react-app-rewired (1.0.5) and the latest version of Create React App (1.0.6)

Our application runs without issues and decorator support is working great. However, when running tests, we get the following errors

Test suite failed to run import 'example-module'; ^^^^^^ SyntaxError: Unexpected token import

I assume it's related to the configuration of Jest, where maybe Babel is not transpiling the tests correctly. We are not doing anything special with running the tests, and our package.json is as recommended in the readme "test": "react-app-rewired test --env=jsdom"

I'm happy to provide any additional information.

Relay Modern

Any plans to upgrade the Relay package to use the new Babel plugin "babel-plugin-relay" which supports Relay Modern?

react-app-rewire-less not working on Windows

When running Node on Windows rewireLess() fails to locate file-loader config because it uses rule.loader.endsWith('/file-loader/index.js') to detect it.

Naturally, on Windows the path separators will be backslashes instead of slashes ('\file-loader\index.js'), and the check will fail. You could use path.sep or just look for 'file-loader' without the index.js part to fix this.

Examples dir

The list of examples as gists is good but these should be Markdown files in an Examples directory IMO. That way they can have a bit of a preamble (like what dependencies to install) and then they end with a code block with the config to cut & paste. And people can more easily submit PRs to tweak them.

Cannot read property 'forEach' in config.module.loaders

After update react-scripts to 1.0.7, I see bug for this code:

module.exports = function override(config, env) {
  var loader = 'style!css?modules&';
  if (env === 'development') {
    loader += 'importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss';
  } else {
    loader += '-autoprefixer&importLoaders=1!postcss';
  }
  // Find the right loader then patch its 'loader' property
  config.module.loaders.forEach(l => {
    if (String(l.test) == String(/\.css$/)) l.loader = loader
  })

  return config;
}

console.log(config.module.loaders) output 'undefined'

Windows Environment

Hi. @timarney
I'm opening this Issue because I'm experiencing an error when using react-app-rewired under windows environment, the error is the following:

webpack.validateSchema is not a function
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-app-rewired start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

There's a problem with the node-gyp package that you use for some internal stuff or some dependency you need but, node-gyp has problem with Window's environment so I can't use react-app-rewired at work (yes, I use windows at work, at the moment).

It's not working even installing the "required stuff" that node-gyp package says it's mandatory for windows:

Install all the required tools and configurations using Microsoft's windows-build-tools using npm install --global --production windows-build-tools from an elevated PowerShell or CMD.exe (run as Administrator).

If you could replace this dependency for something a little more "universal" so, windows users (like me at work) could use this, would be awesome!

Thanks for you time!

Cannot find module 'babel-preset-react-app'

I get this error when I run the tests:

● Test suite failed to run

    Cannot find module 'babel-preset-react-app'

      at Function.Module._resolveFilename (module.js:485:15)
      at Function.resolve (internal/module.js:18:19)
      at Object.<anonymous> (node_modules/react-app-rewired/config/jest/babelTransform.js:21:21)

Actually, I can't seem to find babel-preset-react-app inside my node_modules root folder. I see it's located inside node_modules/react-scripts/node_modules/babel-preset-react-app.

Maybe create-react-app changed the way the dependency is required?

Unable to run scripts/test

When converting our application to rewired, I hit an issue when converting the tests to also use rewired. The error is: "ReferenceError: paths is not defined"

const override = require(paths.projectDir + '/config-overrides');

It looks like it's because it's trying to execute the above line of code before, const paths = require("../config/paths"); has been set.

Bubbling up this assignment fixes the issue, which I have created a pull request here: #78

Thanks for this library, it's freaking awesome.

Flow + babel-plugin-flow-react-proptypes does not work with Jest

// config-overrides.js

const babelLoader = function (conf) {
  return conf.loader === 'babel'
}

function rewire(config, env) {
  const babelrc = config.module.loaders.find(babelLoader).query
  babelrc.plugins = [
    'flow-react-proptypes',
  ].concat(babelrc.plugins || [])
  return config
}

module.exports = rewire

I assume that the type conversion from Flow to PropTypes occurs after Jest.

[Question] What about code splitting in vendors?

Hi, I'm using this in my projects, but I want to use create-react-app.


// optimizations
    new CommonsChunkPlugin({
      children: true,
      async: 'common',
      minChunks: 2,
    }),
    new CommonsChunkPlugin({
      children: true,
      async: 'vendor',
      minChunks(module) {
        // this assumes your vendor imports exist in the node_modules directory
        return isVendor(module);
      },
    }),

Where isVendor is like this:

function isVendor (module) {
  return module.context && module.context.indexOf('node_modules') !== -1;
}

Can I use react-app-rewired for this? Thanks ;)

react-app-rewire-mobx not working with decorator @observable

react-scripts version 1.0.12.

I following the instruction from this link: https://github.com/timarney/react-app-rewired/tree/master/packages/react-app-rewire-mobx

The app will run without decorator. Once I use decorator, I got "Syntax error: C:/.../...js: Unexpected token" at the "@observable".

Did I miss anything?

I tried installing babel-plugin-transform-decorators-legacy and then added config = injectBabelPlugin('transform-decorators-legacy',config); in the config-overrides.js and it didn't work either.

Thanks.

Drop into an existing CRA project

I really like the idea behind this project, but it still kinda feels like a boilerplate — you have to decide to use react-app-rewired instead of create-react-app at the beginning, right?

Would it be possible to wrap this up in a different way, so that you could take a perfectly normal CRA app and then, instead of ejecting, do something like this:

npm i -D react-app-rewired
--- a/package.json
+++ b/package.json
@@ -3,7 +3,8 @@
   "devDependencies": {
-    "react-scripts": "0.7.0"
+    "react-scripts": "0.7.0",
+    "react-app-rewired": "^1.0.0"
   },
@@ -12,9 +13,9 @@
   "scripts": {
-    "start": "react-scripts start",
-    "build": "react-scripts build",
-    "test": "react-scripts test --env=jsdom",
-    "eject": "react-scripts eject"
+    "start": "react-app-rewired start",
+    "build": "react-app-rewired build",
+    "test": "react-app-rewired test --env=jsdom",
+    "eject": "react-app-rewired eject"
   }
 }

Then suddenly your magic config-overrides.js file gets picked up and you're all good. It feels like this API should be totally possible with the work you've already done, but let me know if I'm missing something.

I really want something like this to exist for people to be able to use babel-plugin-styled-components-named without ejecting. Reckon that's possible?

Can i use file.less

Hi, for customizing theme of ant.desing i using react-app-rewired and successfully i can edit and add my customization the to the config-override.js and it's pretty good except when my customization is huge and has may variables, accourding to the ant documentation i use less files, can i use less files with react-app-rewired insideof directly putting my variables in config-overrride.js ?

Cannot read property 'some' of undefined

Hi, i follow this instruction for using react-app-rewired and ant design and create-react-app but after i changed script section of package.json and then run the npm start i get this error :
screenshot from 2017-09-02 09-02-21

that say cant not read property 'some' of undefined, i check the source and i think it maybe cant load babel plugin so i try to re install the babel-plugin-import but the error still happend.

react-app-rewire-less not working

/Users/afc163/Projects/antd-demo-new/node_modules/[email protected]@react-app-rewire-less/index.js:8
  fileLoader.exclude.push(lessExtension);
            ^

TypeError: Cannot read property 'exclude' of undefined
    at rewireLess (/Users/afc163/Projects/antd-demo-new/node_modules/[email protected]@react-app-rewire-less/index.js:8:13)
    at override (/Users/afc163/Projects/antd-demo-new/config-overrides.js:6:12)
    at Object.<anonymous> (/Users/afc163/Projects/antd-demo-new/node_modules/[email protected]@react-app-rewired/scripts/start.js:18:3)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3

Node environment variables not loaded

When using this component, the Node environment file, .env, is being read too late. I created a repo of the issue here: react-rewired-env-issue.

It may be as simple as adding the the dotenv load at the beginning of the start and build scripts:

require('dotenv').config({silent: true});

(This is what the react-scripts do.)

I cannot think of other problems that this might introduce. I'll submit a PR.

interest in react-intl integration?

today I looked into react-intl. It offers a babel plugin for automatically extracting message ids from source code:

https://github.com/yahoo/babel-plugin-react-intl

I managed to use react-app-rewired to integrate it. Here's the code:

const babelLoader = function(conf) {
  return conf.loader === "babel";
};

//webpack2
function rewireIntl(config, env) {
  const babelrc = config.module.loaders.find(babelLoader).query;
  babelrc.plugins = [
    [
      "react-intl",
      {
        messagesDir: "./messages/"
      }
    ]
  ].concat(babelrc.plugins || []);
  return config;
}

module.exports = rewireIntl;

If you're interested I could create a pull request so you can maintain it as part of this project. One question is how to configure it. I've hardcoded "messagesDir" into it for now, and the configuration options aren't that broad, but perhaps people want something more.

SASS rewire deprecatiation

Hi,

I saw that you deprecated the SASS rewire because Create React App added official guide about how to add SASS support. I looked at the guide and it is compiling SASS on the side without using Webpack, so you do not have the benefits of the single dependency tree, and other Webpack stuff. Are we really sure we want to deprecate this rewire for what seems like inferior solution?

Also thanks for creating react-app-rewired, it is really useful addition to the Create React App.

sass example with react-scripts 1.0.11 doesn't work

Tried many different adjustments to the config-overrides.js file, but can't seem to get saas to compile with the current version of react-scripts. It looks like the webpack config files are much different in structure, and also use webpack 3.

I would be glad to help, but want to confirm that this is an issue for others besides myself.

I tried adjusting the config to this, which looks messy but the output looked correct based on the weird oneOf syntax.

config.module.rules[1].oneOf.push({
    test: /\.scss$/,
    use: [
      {
        loader: "style-loader"
      },
      {
        loader: "css-loader"
      },
      {
        loader: "sass-loader",
        options: {
          sourceMap: true
        }
      }
    ]
  });

NODE_PATH doesn't work for tests. Cannot find module

Is this a bug report?

Yes

Can you also reproduce the problem with npm 4.x?

No. Same for latest npm 5 and npm 4.

Environment

  1. node -v: v7.10.1
  2. npm -v: 4.2.0
  3. yarn --version: 0.27.5
  4. npm ls react-scripts: 1.0.11
  5. Operating system: Mac OS 10.12.6

Steps to Reproduce

  1. Set NODE_PATH to NODE_PATH=./ in .env
  2. Try to import like: import Comp from 'src/components/Comp'
  3. yarn start runs fine.
  4. yarn test running tests where their imported modules have such src/.... imports
    P.S. npm run start / test give same results as for yarn

Expected Behavior

Tests should run fine and import all modules with no problems at all.

Actual Behavior

They all fail except those which are never use any dep withsrc/.... imports

Screenshot

Working example.

https://github.com/RIP21/no-env-imports-tests
yarn install && yarn start - that is it.

Tweaking the webpack config is not possible in certain cases.

I was taking a look at updating the LESS loaded for CRA 1.0 with Webpack 2 and I am starting to hit dead ends with the solution react-app-rewired provides

Take a look at the following line
https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/webpack.config.prod.js#L210

Or this line
https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/webpack.config.prod.js#L231-L234

There are parts of the webpack config, that I would like to modify but can't because they are wrapper in functions that are evaluated.

I am not sure what the proper solution for this is, maybe have a way to replace exact lines of the config before running it? Maybe something like:

reactAppRewired.replaceLine({
  start: 231,
  end: 234,
  newContent: `
    '>1%',
    4 versions',
    android >= 4
    ESR',
    ie < 9',
  `
})

But that seems fragile. Not sure what the correct solution is.

Better npm scripts

So it should be possible, instead of having the following in the package.json

    "rewire:start": "node ./node_modules/react-app-rewired/scripts/start",
    "rewire:build": "node ./node_modules/react-app-rewired/scripts/build"

to have this:

    "rewire:start": "react-app-rewired start",
    "rewire:build": "react-app-rewired build"

Also means that you could just replace the package names of the default entry points if you prefer (I do! 😄 )

-    "start": "react-scripts start",
-    "build": "react-scripts build",
+    "start": "react-app-rewired start",
+    "build": "react-app-rewired build",

Sass example doesn't work

I'm adding this to my new config file

module.exports = function override(config, env) {
  config.module.loaders.push({
	test: /\.scss$/,
	loaders: ["style", "css", "sass"]
  });
  console.log(config.module.loaders)
  return config;
}

But the styles are lost when testing the app.

I'm importing the new scss files, but nothing happens.

Broken when used with lerna bootstrap --hoist

Lerna bootstrap --hoist moves all shared node_modules deps of packages into the lerna root directory.

react-app-rewired (RAR) is building the create react app (CRA) webpack path from cwd of the project being built, which node_modules folder won't have either CRA or RAR, so it chokes.

Will need to resolve CRA's webpack config from RAR's node modules location.
build.js -
const webpackConfig = paths.scriptVersionDir + '/config/webpack.config.prod';

Creating Rewired module instead of just example

Hey! What do you think about creating small modules for common configs in this project? Then instead of just having people could just use the modules or look at the source code in case they want anything super fancy.

ex:

import { rewireSass, rewireRelay } from 'react-app-rewired';

module.exports = function override(config, env) {
  return rewireRelay(rewireSass(config, env), env);
};

Getting module not found errors on react-tap-event-plugin

I decided to post the issue here rather than on twitter.

I'm using custom-react-scripts.

react-tap-event-plugin is version 2.0.1
react/react-dom version is 15.6.1

Here is my package.json - https://gist.github.com/c0debreaker/d3cbfe856e4807edd5a859a5c0231c8c

I'm getting this error when I run npm run start.

Error in ./~/react-tap-event-plugin/src/injectTapEventPlugin.js
Module not found: 'preact-compat/lib/EventPluginHub' in /Users/rcamara/repos/AllReact/dashboard/node_modules/react-tap-event-plugin/src

 @ ./~/react-tap-event-plugin/src/injectTapEventPlugin.js 23:2-41

Error in ./~/react-tap-event-plugin/src/TapEventPlugin.js
Module not found: 'preact-compat/lib/EventConstants' in /Users/rcamara/repos/AllReact/dashboard/node_modules/react-tap-event-plugin/src

 @ ./~/react-tap-event-plugin/src/TapEventPlugin.js 22:21-60

Error in ./~/react-tap-event-plugin/src/TapEventPlugin.js
Module not found: 'preact-compat/lib/EventPluginUtils' in /Users/rcamara/repos/AllReact/dashboard/node_modules/react-tap-event-plugin/src

 @ ./~/react-tap-event-plugin/src/TapEventPlugin.js 23:23-64

Error in ./~/react-tap-event-plugin/src/TapEventPlugin.js
Module not found: 'preact-compat/lib/EventPropagators' in /Users/rcamara/repos/AllReact/dashboard/node_modules/react-tap-event-plugin/src

 @ ./~/react-tap-event-plugin/src/TapEventPlugin.js 24:23-64

Error in ./~/react-tap-event-plugin/src/TapEventPlugin.js
Module not found: 'preact-compat/lib/SyntheticUIEvent' in /Users/rcamara/repos/AllReact/dashboard/node_modules/react-tap-event-plugin/src

 @ ./~/react-tap-event-plugin/src/TapEventPlugin.js 25:23-64

Error in ./~/react-tap-event-plugin/src/TapEventPlugin.js
Module not found: 'preact-compat/lib/ViewportMetrics' in /Users/rcamara/repos/AllReact/dashboard/node_modules/react-tap-event-plugin/src

 @ ./~/react-tap-event-plugin/src/TapEventPlugin.js 27:22-62

react-scripts 1.0

react-scripts 1.0 is coming with some great improvements. See #2171
As it is moving to webpack 2,
is there any plan to support it in react-app-rewired ?

rule.loader.endsWith is not a function

if (env === 'production') {
lessRules = {
test: lessExtension,
loader: [

In "production" I get this error:

node_modules/react-app-rewire-less/index.js:8
    config.module.rules, rule => rule.loader && rule.loader.endsWith(`file-loader${path.sep}index.js`)
                                                            ^
TypeError: rule.loader.endsWith is not a function
    at rule (/contextubot/node_modules/react-app-rewire-less/index.js:8:61)
    at rules.some.rule (/contextubot/node_modules/react-app-rewired/index.js:9:21)
    at Array.some (<anonymous>)
    at getLoader (/contextubot/node_modules/react-app-rewired/index.js:8:9)
    at rules.some.rule (/contextubot/node_modules/react-app-rewired/index.js:11:9)

I guess rule.loader.endsWith does not work on Arrays (loader: […).

How to customize babel with react-scripts v1 (webpack v2)

before:

// config-overrides.js

function rewire(config, env) {
  const babelrc = config.module.loaders.find(conf => {
    return conf.loader === 'babel'
  }).query
  babelrc.plugins = [
    'styled-jsx-postcss/babel',
  ].concat(babelrc.plugins || [])
  return config
}

module.exports = rewire

after:

// config-overrides.js

function rewire(config, env) {
  const babelOptions = config.module.rules.find(conf => {
    return conf.loader && conf.loader.includes('babel-loader')
  }).options
  const babelrc = require(babelOptions.presets[0])
  babelrc.plugins = [
    'styled-jsx-postcss/babel',
  ].concat(babelrc.plugins || [])
  babelOptions.presets = babelrc
  return config
}

module.exports = rewire

happy coding!

Create tests for the supported react-scripts version

I think we can create tests reading the config and asserting if the right values are there for each rewire. This way when react-script upgrades we can be sure that our code still works.

I can do this. hehe

node version requirement?

I've been using version 0.53 with react-app-rewire-mobx 0.1.0 (thanks!) but when I upgraded to a newer version I get an error about "let" being used on the top level and that this isn't supported. I suspect this means my (operating system supplied) node is too old; I've been using 4.7.3.

So while it's probably just a matter of me having to upgrade Node, I haven't had issues with the rest of the toolchain, so if it isn't a large hassle it might be worthwhile to adjust things. If not, a minimal node version would be nice to specify. (if it's indeed node)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.