Giter Site home page Giter Site logo

create-react-app-esbuild's Introduction

🚀 create-react-app-esbuild 🚀

Use esbuild in your create-react-app for faster compilation, development and tests.

Features

  • Replace babel-loader with esbuild during development
  • Replace babel-loader with esbuild for faster build time
  • Replace terser with esbuild for faster build time
  • Replace OptimizeCssAssetsWebpackPlugin with esbuild for faster build time
  • Use esbuild when running jest

Getting started

Follow the guide to setup your project.

FAQ

Why is it faster?

Internally create-react-app use babel to compile the javascript / typescript files of your application. By using craco-esbuild, you use the esbuild compiler to compile your app instead of babel. esbuild is a super fast javascript / typescript bundler and minifier written in Go.

What is craco and why do I need it?

craco (Create React App Configuration Override) is an easy and comprehensible configuration layer for create-react-app. By using craco you can customise the create-react-app configuration without ejecting.

License

MIT © Léo Pradel

create-react-app-esbuild's People

Contributors

crecket avatar dbuezas avatar github-actions[bot] avatar jiejasonliu avatar kobim avatar lpillonel avatar mariobm avatar ottob avatar pradel avatar randuck-dev avatar spiftire avatar yaronya 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

create-react-app-esbuild's Issues

ReferenceError: React is not defined

System

Windows 10, tested on FF and Chrome.

Steps to reproduce:

  1. run npx create-react-app appName
  2. run npm install --save-dev craco-esbuild @craco/craco
  3. Change scripts:
"scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  },
  1. Create craco.config.js:
const CracoEsbuildPlugin = require("craco-esbuild");

module.exports = {
  plugins: [
    {
      plugin: CracoEsbuildPlugin,
      options: {
        esbuildLoaderOptions: {
          loader: "jsx",
          target: "es2015",
        },
      },
    },
  ],
};
  1. Run npm start

Also tested with simpler craco.config.js:

const CracoEsbuildPlugin = require("craco-esbuild");

module.exports = {
  plugins: [{ plugin: CracoEsbuildPlugin }],
};

Expected result

Should show the standart CRA page.
Everything works correctly if I change the start script back to "start": "react-scripts start"

Actual Result

Browser displays the following error message:

ReferenceError: React is not defined
App
C:/dev/craco/app/src/App.js:5

  2 | import './App.css';
  3 | 
  4 | function App() {
> 5 |   return (
  6 |     <div className="App">
  7 |       <header className="App-header">
  8 |         <img src={logo} className="App-logo" alt="logo" />

./src/index.js/<
C:/dev/craco/app/src/index.js:7

   4 | import App from "./App";
   5 | import reportWebVitals from "./reportWebVitals";
   6 | 
>  7 | ReactDOM.render(
   8 |   <React.StrictMode>
   9 |     <App />
  10 |   </React.StrictMode>,

./src/index.js
http://localhost:3000/static/js/main.chunk.js:446:30
__webpack_require__
C:/dev/craco/app/webpack/bootstrap:856

  853 | 
  854 | __webpack_require__.$Refresh$.init();
  855 | try {
> 856 | 	modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  857 | } finally {
  858 | 	__webpack_require__.$Refresh$.cleanup(moduleId);
  859 | }

fn
C:/dev/craco/app/webpack/bootstrap:150

  147 | 		);
  148 | 		hotCurrentParents = [];
  149 | 	}
> 150 | 	return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 | 	return {

1
http://localhost:3000/static/js/main.chunk.js:576:18
__webpack_require__
C:/dev/craco/app/webpack/bootstrap:856

  853 | 
  854 | __webpack_require__.$Refresh$.init();
  855 | try {
> 856 | 	modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  857 | } finally {
  858 | 	__webpack_require__.$Refresh$.cleanup(moduleId);
  859 | }

checkDeferredModules
C:/dev/craco/app/webpack/bootstrap:45

  42 | 	}
  43 | 	if(fulfilled) {
  44 | 		deferredModules.splice(i--, 1);
> 45 | 		result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 | 	}
  47 | }
  48 | 

webpackJsonpCallback
C:/dev/craco/app/webpack/bootstrap:32

  29 | 	deferredModules.push.apply(deferredModules, executeModules || []);
  30 | 
  31 | 	// run deferred modules when all chunks ready
> 32 | 	return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 | 	var result;

(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:59
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.  Click the 'X' or hit ESC to dismiss this message.

Misc

I also tried using https://github.com/pradel/create-react-app-swc and I get exactly the same error message.

`esbuild-jest` file patterns are wrong

esbuild-jest file load patterns are currently set to:

loaders: {
	  '.js': 'jsx',
	  '.test.js': 'jsx',
	  '.ts': 'tsx',
	  '.test.ts': 'tsx',
}

This might be wrong because .ts file just get the 'tsx' loader and not ts.
When using tsx for .ts I get a lot of transformation errors.

Latest version throws an unexpected token error

Hi there.

The latest version (0.4.0) doesn't compile when launching the start command (craco start, I haven't tested the other commands). This is what's getting printed on the console:

UnhandledPromiseRejectionWarning: /Users/<readacted>/repro-cra-craco-esbuild-bug/node_modules/craco-esbuild/src/index.js:65
    const minimizerOptions = pluginOptions?.esbuildMinimizerOptions || {
                                           ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)

I have put together a simple repro. You can check it out here → https://github.com/madiodio/repro-cra-craco-esbuild-bug

Async Jest tests run into issue

Hi, thanks for this project!
I'm having an issue I can't seem to fix: all my Jest tests are passing BUT as soon as there is some async in there, it stops working, having a ReferenceError: regeneratorRuntime is not defined.

script in package.json: craco test

Here is my craco.config.js:

const CracoEsbuildPlugin = require('craco-esbuild');

module.exports = {
  plugins: [{
    plugin: CracoEsbuildPlugin, options: {
      esbuildLoaderOptions: {
        loader: 'jsx',
        target: 'es2015',
      }
    }
  }]
};

Error:
image

And when I run it with a Jest configuration (with Babel) there is no issue. Any leads?
Thanks!

edit: I dug into the issue and the case is well documented for Babel, needing to add polyfill and/or regenerator. But having low experience with esbuild, I don't know how the polyfills work, especially with create-react-app-esbuild as a wrapper.

With React 17, i get error, React is not defined.

With React 17 i get error, React is not defined.
My craco.config.js is the minimal as suggested by the guide.

const CracoEsbuildPlugin = require('craco-esbuild');

module.exports = {
  plugins: [{ plugin: CracoEsbuildPlugin }],
};

Please note that i don't have

import React from "react";

Because it's not needed in react 17+

Use with ant design/less

Hi,

I use the popular Ant Design UI library in my project and for some reason after adding craco-esbuild (which is 2x faster than babel, woohoo!) I'm unable to control the customized theme provider by antd (they use less for that). It seems that the output bundle doesn't include the compiled css rules.

I'm not even sure why this happens, as this package replaces babel and less files are handled by webpack anyways 🤔

Would be superb if you have any lead/suggestion on that 🙏

CSS optimization

In the es-build documentation there is an option to use the ESBuildMinifyPlugin for CSS minification here.

This module doesn't seem to take advantage of that.

Thanks for the convenience of this anyway! :)

How to resolve aliases via Typescript paths?

Thanks for this great plugin!

Is there a way to have it resolve aliases via the Typescript paths setting in tsconfig.json?

Out of the box, code that compiles fine with rescripts start does not compile with the setup described in the readme here (i.e. just CracoEsbuildPlugin configured in craco.config.js, nothing else) and craco start -- compilation fails on module resolution for any alias.

I noticed that esbuild itself theoretically has support for this (see here) though apparently not without the --bundle flag set. Is that the limitation here? Or is this something that needs to be configured in some particular way for craco?

Attempting to use imported components that use SVG fails in Jest

Hi there, another question if you have a second! I have components that render imported SVG files as components. These components are then imported into the jest test files. When running my test, I receive the following error:

Cannot create styled-component for component: [object Object].

My test code looks like this:

it('should render an icon', () => {
  const IconToRender = styled(getIcon('Copy'))`` // this is supposed to return an imported SVG icon, but instead throws the error below.
  const {container} = render(<IconToRender />)
  const iconSVG = container.querySelector('svg')
  expect(iconSVG).toBeTruthy()
})

I think this is an issue with the svgr functionality. My config looks like this:

options: {
  enableSvgr: true,
}

But I don't think that matters, because upon inspecting this plugin's code, enableSvgr is only active inside the overrideWebpackConfig codepath. It might also be worth mentioning that these icons render just fine in the browser.

Any ideas?

Question: Possible to use babel transforms

This is probably a silly question but is it possible to use babel transforms with the plugin?

I added this plugin to the craco config and it made the build and dev mode very fast! Great work 😃

However after using this, I noticed that my babel plugins were no longer working. Including this [babel plugin used for removing test ids]((https://www.npmjs.com/package/babel-plugin-react-remove-properties)

This makes sense I guess because this replaces babel-loader... but I'm wondering if there is a way to make both work. FAST builds with esbuild and babel transforms.

Is this possible? Thanks!

// some of my craco.config
{
    babel: {
      plugins: [
        ...(isDevBuild ? ['babel-plugin-style-guard'] : []),
        ...(isProdContext ? [['react-remove-properties', { properties: ['data-testid'] }]] : []),
      ],
    },
    plugins: [
      {
        plugin: CracoEsbuildPlugin,
      },
    ]

Test run fails with "Transform failed with 1 error:..."

I am getting the following error when running tests.

  ● Test suite failed to run

    Transform failed with 1 error:
    <stdin>:986:4: error: Unexpected "return"

      at failureErrorWithLog (node_modules/esbuild/lib/main.js:1275:15)
      at sendRequest (node_modules/esbuild/lib/main.js:1094:33)
      at responseCallbacks.set (node_modules/esbuild/lib/main.js:576:9)
      at handleIncomingPacket (node_modules/esbuild/lib/main.js:665:9)
      at readFromStdout (node_modules/esbuild/lib/main.js:543:7)
      at runServiceSync (node_modules/esbuild/lib/main.js:1591:3)
      at Object.transformSync (node_modules/esbuild/lib/main.js:1421:3)
      at Object.process (node_modules/esbuild-jest/esbuild-jest.js:54:36)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:453:35)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:523:40)

The main build works fine and is configured like so:

module.exports = {
    plugins: [
        {
            plugin: CracoEsbuildPlugin,
            options: {
                enableSvgr: true,
                esbuildLoaderOptions: {
                    loader: "tsx",
                    target: "es2017",
                },
            },
        },
  // ...

I noticed that esbuild-jest has a note about when using "paths" in tsconfig.json. I do not have "paths" set in my tsconfig.json, but am using "baseUrl" to resolve non-relative modules. Could that have anything to do with this error?

craco babel settings not working @emotion/react

// emotion css prop is not working
module.exports = {
  babel: {
    presets: [
      [
        '@babel/preset-react',
        {'runtime': 'automatic', 'importSource': '@emotion/react'}
      ]
    ],
    plugins: ['@emotion/babel-plugin']
  },
  plugins: [
    {
      plugin: CracoEsbuildPlugin,
    },
    ...
  ],
}

// it works
module.exports = {
  babel: {
    presets: [
      [
        '@babel/preset-react',
        {'runtime': 'automatic', 'importSource': '@emotion/react'}
      ]
    ],
    plugins: ['@emotion/babel-plugin']
  },
  ... // use the default babel settings of react-script instead of esbuild
}

When I use craco esbuild, cannot use css props in emotion.
Is the craco esbuild plugin clearing babel settings?

`yarn run start` fails with UnhandledPromiseRejectionWarning

I'm not having much luck with Google or Github on this issue so that leads me to believe it might be specific to this project. Am on [email protected], unejected.

Using a very basic configuration:

const CracoEsbuildPlugin = require('craco-esbuild')

module.exports = {
  plugins: [
    {
      plugin: CracoEsbuildPlugin,
    },
  ],
}

Upon running craco start, I receive the following error:

(node:78044) UnhandledPromiseRejectionWarning: Error: Cannot find module 'webpack/lib/ModuleFilenameHelpers'
Require stack:
- /Users/me/dev/myproject/node_modules/esbuild-loader/dist/minify-plugin.js
- /Users/me/dev/myproject/node_modules/esbuild-loader/dist/index.js
- /Users/me/dev/myproject/node_modules/craco-esbuild/src/index.js
- /Users/me/dev/myproject/packages/frontend/craco.config.js
- /Users/me/dev/myproject/node_modules/@craco/craco/lib/config.js
- /Users/me/dev/myproject/node_modules/@craco/craco/scripts/start.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:831:15)
    at Function.Module._load (internal/modules/cjs/loader.js:687:27)
    at Module.require (internal/modules/cjs/loader.js:903:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/Users/me/dev/myproject/node_modules/esbuild-loader/dist/minify-plugin.js:5:33)
    at Module._compile (internal/modules/cjs/loader.js:1015:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
    at Module.load (internal/modules/cjs/loader.js:879:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:903:19)
(node:78044) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:78044) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```

TypeError: Cannot read properties of undefined (reading 'findIndex')

Got the the following error when running craco start:

/xxx/node_modules/craco-esbuild/src/index.js:13
  const idx = webpackConfig.optimization.minimizer.findIndex(
                                                   ^

TypeError: Cannot read properties of undefined (reading 'findIndex')
    at replaceMinimizer (/xxx/node_modules/craco-esbuild/src/index.js:13:52)
    at Object.overrideWebpackConfig (/xxx/node_modules/craco-esbuild/src/index.js:58:5)
    at overrideWebpack (/xxx/node_modules/@craco/craco/dist/lib/features/plugins.js:36:38)
    at /xxx/node_modules/@craco/craco/dist/lib/features/plugins.js:53:29
    at Array.forEach (<anonymous>)
    at applyWebpackConfigPlugins (/xxx/node_modules/@craco/craco/dist/lib/features/plugins.js:52:29)
    at mergeWebpackConfig (/xxx/node_modules/@craco/craco/dist/lib/features/webpack/merge-webpack-config.js:119:70)
    at overrideWebpackDev (/xxx/node_modules/@craco/craco/dist/lib/features/webpack/override.js:8:80)
    at /xxx/node_modules/@craco/craco/dist/scripts/start.js:23:39

Node.js v18.18.2
❌ Failed to start dev server (exit status 1)

Significant size differences

Firstly thanks for the great plugin!

I was looking at potentially migrating our codebase to utilise esbuild and noticed that a compiled build was significantly larger than without esbuild. That is to say more than 2.5x larger than the output without esbuild, as below.

With standard CRA/Webpack:

File sizes after gzip:

  152.72 KB (-259.17 KB)  public_html\static\js\2.726246eb.chunk.js
  16.54 KB (-6.71 KB)     public_html\static\js\main.b3737a8f.chunk.js
  1.44 KB (+14 B)         public_html\static\css\2.60d63202.chunk.css
  776 B (-6 B)            public_html\static\js\runtime-main.f6cb6938.js
  641 B                   public_html\static\css\main.275971f0.chunk.css

With Esbuild:

File sizes after gzip:

  411.88 KB  public_html\static\js\2.ae05d37c.chunk.js
  23.25 KB   public_html\static\js\main.51dab84a.chunk.js
  1.42 KB    public_html\static\css\2.60d63202.chunk.css
  782 B      public_html\static\js\runtime-main.1ccb1639.js
  641 B      public_html\static\css\main.275971f0.chunk.css

In the grand scheme of things, a couple of hundred KB isn't that huge of a deal but I'm wondering if this is perhaps due to misconfiguration or something else that perhaps I missed?

Below is my craco configuration for reference:

const isCoverage = process.env.COVERAGE === "true";
const babelPlugins = isCoverage ? ["babel-plugin-istanbul"] : [];

module.exports = {
    babel: {
        plugins: babelPlugins,
    },
    plugins: [
        {
            plugin: require("craco-alias"),
            options: {
                source: "tsconfig",
                baseUrl: "./src",
                tsConfigPath: "./tsconfig.aliases.json",
            },
        },
        {
            plugin: require("craco-esbuild"),
            options: {
                enableSvgr: true,
                esbuildMinimizerOptions: {
                    target: "es6",
                    css: true,
                    minify: true,
                },
                skipEsbuildJest: true,
            },
        },
    ],
};

All other configurations can also be found here.

[Question] how does one translate usage of `.babelrc` with esbuild?

We use the below .babelrc. I'm having trouble understanding what gets replaced by switching to esbuild. Just following the basic craco replacements doesn't work for me. I immediately run into:

Expected "from" but found "{"

Which I suspect might be a different issue than babel, possibly cause we're using flow and we import types, e.g. import type { GlobalStore } from "app/redux".

{
  "presets": ["@babel/preset-flow", "@babel/preset-react", "@babel/preset-env"],
  "plugins": [
    "dynamic-import-node",
    "@babel/plugin-syntax-dynamic-import",
    "@babel/plugin-syntax-import-meta",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-json-strings",
    [
      "@babel/plugin-proposal-decorators",
      {
        "legacy": true
      }
    ],
    "@babel/plugin-proposal-function-sent",
    "@babel/plugin-proposal-export-namespace-from",
    "@babel/plugin-proposal-numeric-separator",
    "@babel/plugin-proposal-throw-expressions",
    "@babel/plugin-proposal-nullish-coalescing-operator"
  ]
}

Any help to further understand this migration would be great!

JSX syntax extension is not enabled

When I run craco test "--watchAll=false", I get the following error in one of my tests:

<stdin>:69:11: ERROR: The JSX syntax extension is not currently enabled

Here's how my craco.config.js looks like:

module.exports = {
  plugins: [
    {
      plugin: CracoEsbuildPlugin,
      options: {
        esbuildLoaderOptions: {
          loader: "tsx", // Set the value to 'tsx' if you use typescript
          target: "es2015",
        },
        esbuildMinimizerOptions: {
          target: "es2015",
          css: true, // if true, OptimizeCssAssetsWebpackPlugin will also be replaced by esbuild.
        },
        skipEsbuildJest: false, // Optional. Set to true if you want to use babel for jest tests,
        esbuildJestOptions: {
          loaders: {
            ".ts": "ts",
            ".tsx": "tsx",
          },
        },
      },
    },
  ],
  webpack: {
    configure: (webpackConfig, { env }) => {
      const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
        ({ constructor }) => constructor && constructor.name === "ModuleScopePlugin",
      );

      webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);

      if (env === "development") {
        const fileLoader = {
          test: /\.(png|jpe?g|gif|svg|woff|woff2|webp)$/i,
          use: [
            {
              loader: "url-loader",
              options: {
                limit: 256000,
              },
            },
          ],
        };
        addBeforeLoader(webpackConfig, loaderByName("url-loader"), fileLoader);
      }

      return env === "development" ? webpackConfig : smp.wrap(webpackConfig);
    },
  },
  babel: {
    plugins: [
      [
        "@simbathesailor/babel-plugin-use-what-changed",
        {
          active: process.env.NODE_ENV === "development", // boolean
        },
      ],
    ],
  },
};

If I set skipEsbuildJest to true, then all the tests pass.

Can you tell me if I'm doing something wrong or if it's a bug in the package?

SVGR import not working

SVG import is not working (import as a ReactComponent):

'ReactComponent' is not exported from ''../../../../assets/star.svg' (imported as 'Star').

SVGR is included by default in CRA 4.

import { ReactComponent as StarSvg } from '../../../../assets/star.svg'

Craco config as simple as:

// craco.config.js
const CracoEsbuildPlugin = require("craco-esbuild");

module.exports = {
  plugins: [{ plugin: CracoEsbuildPlugin }],
};

Why is it still using Webpack, or is it broken?

I first tested in a much more evolved but still CRA based with TypeScript project. Didn't seem to be using esbuild. The yarn build still took ~10s.

Start a fresh new project:

cd /tmp/
npx create-react-app@latest my-ts-app --template typescript
cd my-ts-app
yarn build
# takes about ~5s

Then I followed the steps in the readme verbatim. And when I type yarn build you can see that it's supposedly using craco:

▶ yarn build
yarn run v1.22.10
$ craco build
Creating an optimized production build...
Compiled successfully.

File sizes after gzip:
...

But still takes about ~5s to build. I don't know what I'm doing but I did open node_modules/react-scripts/scripts/build.js and with some scatter console.log it seems it's still using webpack.

Is it busted at the moment? Or is something missing in the readme?

Unable to use TypeScript

I'm using typescript and followed the getting started https://github.com/pradel/create-react-app-esbuild/blob/main/packages/craco-esbuild/README.md

App.tsx

const { isLoading } = useQuery<FetchUserQueryResponse, Error>({
    queryKey: 'user', 
    queryFn: fetchUser,
});
Failed to compile.

./src/Components/App/App.tsx
Error: Transform failed with 1 error:
client/src/Components/App/App.tsx:38:64: error: Expected ";" but found ">"

craco.config.js

const CracoEsbuildPlugin = require('craco-esbuild');
const { ProvidePlugin } = require('webpack');

module.exports = {
    webpack: {
        plugins: [
            new ProvidePlugin({
                React: 'react',
            }),
        ],
    },
    plugins: [
        {
            plugin: CracoEsbuildPlugin,
            options: {
                enableSvgr: true, // Optional.
                esbuildLoaderOptions: {
                    loader: 'jsx',
                    target: 'es2015',
                },
            },
        },
    ],
    style: {
        postcss: {
            plugins: [require('tailwindcss'), require('autoprefixer')],
        },
    },
};

craco build errorring out on nullish Coalescing

Issue: craco build throws this error:

versions:
craco 5.9.0
craco-esbuild 0.5.1

`
./node_modules/vega-label/build/vega-label.module.js 557:33
Module parse failed: Unexpected token (557:33)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| return false;
| }

let textWidth = d.textWidth ?? 0,

| dx,
| dy,
`

// craco.config.js
`
const CracoEsbuildPlugin = require('craco-esbuild');

module.exports = {
plugins: [{ plugin: CracoEsbuildPlugin }]
};
`

I tried using the target in craco.config.js but no success.

Any advice ?

Hope to add a proxy option

我发现无法正常使用live-server的代理功能,经过测试发现通过以下方法修改之后可以正常使用代理功能了
I found that the proxy function of the live-server cannot be used normally. After testing, I found that the proxy function can be used normally after modification by the following method:
具体方法:
specific method:
添加proxy定义,具体位置如下图
image
proxy?: string[][] | undefined;
增加配置项:
image

Does not install - unable to resolve dependency tree

It is currently not possible to install craco-esbuild.

Steps to reproduce:

  1. Using node v 16.6.2

H:\nvm list

  • 16.6.2 (Currently using 64-bit executable)
    16.6.0
    13.5.0
    12.13.0
    10.14.1
    8.8.0
  1. Create new project with npm init

  2. Try to install: H:\test_clean>npm install --save-dev craco-esbuild @craco/craco
    npm ERR! code ERESOLVE
    npm ERR! ERESOLVE unable to resolve dependency tree
    npm ERR!
    npm ERR! While resolving: [email protected]
    npm ERR! Found: [email protected]
    npm ERR! node_modules/react-scripts
    npm ERR! peer react-scripts@"^4.0.0" from @craco/[email protected]
    npm ERR! node_modules/@craco/craco
    npm ERR! dev @craco/craco@"" from the root project
    npm ERR! peer @craco/craco@"^6.0.0" from [email protected]
    npm ERR! node_modules/craco-esbuild
    npm ERR! dev craco-esbuild@"
    " from the root project
    npm ERR!
    npm ERR! Could not resolve dependency:
    npm ERR! peer react-scripts@"^5.0.0" from [email protected]
    npm ERR! node_modules/craco-esbuild
    npm ERR! dev craco-esbuild@"*" from the root project
    npm ERR!
    npm ERR! Fix the upstream dependency conflict, or retry
    npm ERR! this command with --force, or --legacy-peer-deps
    npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Jest tests aren't working

Compilation of the project works fine but as soon as try to run tests it fails with an odd syntax error that is not present when the craco-esbuild is disabled in craco.config.js.
Perhaps there is a way to add this plugin for build & start leaving tests as is?
Any help would be appreciated.

yarn test
yarn run v1.22.10
$ craco test --watchAll=false
 FAIL  src/utils/__test__/utils.spec.ts
  ● Test suite failed to run

    Transform failed with 1 error:
    <stdin>:59:4: error: Expected "}" but found ":"

      at failureErrorWithLog (node_modules/esbuild/lib/main.js:1443:15)
      at node_modules/esbuild/lib/main.js:1254:29
      at node_modules/esbuild/lib/main.js:606:9
      at handleIncomingPacket (node_modules/esbuild/lib/main.js:703:9)
      at readFromStdout (node_modules/esbuild/lib/main.js:573:7)
      at runServiceSync (node_modules/esbuild/lib/main.js:1808:3)
      at Object.transformSync (node_modules/esbuild/lib/main.js:1650:3)
      at Object.process (node_modules/esbuild-jest/esbuild-jest.js:54:36)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:464:35)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:569:40)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:607:25)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.565 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I am using react-scripts 4.0.3

variances in typescript checking times

Hi
I've only started playing with craco and this plugin tonight, so I may well be missing something pretty obvious.

We have a large CRA typescript project which I'm experimenting with. The craco.config.js looks as follows:

// craco.config.js
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const CracoEsbuildPlugin = require("craco-esbuild");
const smp = new SpeedMeasurePlugin();
const { ProvidePlugin } = require('webpack');

module.exports = {
  webpack: {
    configure: (webpackConfig) => smp.wrap(webpackConfig),
  },
  plugins: [
    {
      plugin: CracoEsbuildPlugin,
    }
  ],

};

If I disable CracoEsbuildPlugin and run

GENERATE_SOURCEMAP=false INLINE_RUNTIME_CHUNK=false IMAGE_INLINE_SIZE_LIMIT=0 NODE_OPTIONS=--max-old-space-size=4096 craco build

I get the following

 SMP  ⏱  
General output time took 1 min, 33.73 secs

 SMP  ⏱  Plugins
TerserPlugin took 37.81 secs
ForkTsCheckerWebpackPlugin took 21.21 secs
IgnorePlugin took 3.79 secs
ESLintWebpackPlugin took 2.19 secs
OptimizeCssAssetsWebpackPlugin took 0.752 secs
HtmlWebpackPlugin took 0.13 secs
ManifestPlugin took 0.005 secs
MiniCssExtractPlugin took 0.002 secs
InterpolateHtmlPlugin took 0.001 secs
DefinePlugin took 0.001 secs
ModuleNotFoundPlugin took 0 secs

 SMP  ⏱  Loaders
babel-loader took 29.52 secs
  module count = 2247
modules with no loaders took 7.43 secs
  module count = 119
mini-css-extract-plugin, and 
css-loader, and 
postcss-loader took 2.43 secs
  module count = 1
css-loader, and 
postcss-loader took 1.39 secs
  module count = 6
url-loader took 0.097 secs
  module count = 1
html-webpack-plugin took 0.023 secs
  module count = 1

with CracoEsbuildPlugin enabled I'm seeing

 SMP  ⏱  
General output time took 1 min, 27.34 secs

 SMP  ⏱  Plugins
ForkTsCheckerWebpackPlugin took 1 min, 4.92 secs
IgnorePlugin took 2.31 secs
ESLintWebpackPlugin took 1.89 secs
HtmlWebpackPlugin took 0.116 secs
ManifestPlugin took 0.006 secs
MiniCssExtractPlugin took 0.006 secs
InterpolateHtmlPlugin took 0.001 secs
ModuleNotFoundPlugin took 0 secs
DefinePlugin took 0 secs

 SMP  ⏱  Loaders
modules with no loaders took 15.49 secs
  module count = 1780
esbuild-loader took 11.15 secs
  module count = 522
mini-css-extract-plugin, and 
css-loader, and 
postcss-loader took 1.8 secs
  module count = 1
css-loader, and 
postcss-loader took 1.1 secs
  module count = 6
url-loader took 0.116 secs
  module count = 1
html-webpack-plugin took 0.015 secs
  module count = 1

so whilst esbuild is quiker (yay!) ForkTsCheckerWebpackPlugin is approx 3 times longer and modules with no loaders twice as long

I'm stumped as to why I'm seeing such a difference here - does anyone have any ideas?

Thanks!

Asyn generator issue in esbuild

static/js/main.c648aac4.js:78597:0: ERROR: Transforming async generator functions to the configured target environment ("es2015") is not supported yet

Followed the same setup config in this repo but faced the above issue.

React is not defined

Hi

I used your guide to migrate to CRA + esbuild.

I have a simple component in my source:

import Dummy from './Dummy'

const jsxSingleElement = <Dummy />

export default jsxSingleElement

And after upgrading to your library I receive this error:

Uncaught ReferenceError: React is not defined
    at ./src/Components/React/JsxSingleElement.js (JsxSingleElement.js:3:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/Components/React/Render.js (JsxSingleElement.js:5:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/Panel/Test.js (Styles.js:3:1)
    at options.factory (react refresh:6:1)

And when I remove this file, it keeps complaining about React is not defined in all of my components one after the other.

This is my craco.config.js:

const path = require(`path`);
const aliases = {
  '@Form': 'src/Components/Form/Exports',
  '@List': 'src/Components/List/Exports',
  '@Browse': 'src/Components/Browse/Browse',
  '@Tree': 'src/Components/Tree/Exports',
  '@Tab': 'src/Components/Tab/Exports',
  '@Dashboard': 'src/Components/Dashboard/Dashboard',
  '@Panel': 'src/Panel/Panel',
};

const resolvedAliases = Object.fromEntries(
  Object.entries(aliases).map(([key, value]) => [key, path.resolve(__dirname, value)]),
);

const CracoEsbuildPlugin = require('craco-esbuild');

module.exports = {
  plugins: [{ plugin: CracoEsbuildPlugin }],
  // eslint: {
  //   enable: false
  // },
  webpack: {
    alias: resolvedAliases,
    // this config, causes HolismIcon to throw react error 321 for builds
    configure: {
      resolve: {
        symlinks: false,
      },
    },
  },
}

What am I doing wrong? How can I fix this bug?

Support for babel plugins

Just a feature suggestion. Instead of dropping babel-loader, it can be used together with esbuild-loader:

// define esbuild-loader
const esbuildLoader = {
  // These could be used for the patched babel-loader
  // test: /\.(js|mjs|jsx|ts|tsx)$/,
  // include: [paths.appSrc, ...optionalIncludes],
  loader: require.resolve('esbuild-loader'),
  options: esbuildLoaderOptions
    ? esbuildLoaderOptions
    : {
        loader: useTypeScript ? 'tsx' : 'jsx',
        target: 'es2015',
      },
};

// modify babel loader
const babelLoaderPrev = getLoader(
  webpackConfig,
  loaderByName('babel-loader')
).match.loader;

const { loader, options } = babelLoaderPrev;

const babelLoader = { loader, options };

// Only keep styled-components plugin, drop the rest
options.presets = [];
options.plugins = ['babel-plugin-styled-components'];

const babelEsbuildLoader = babelLoaderPrev;

// Switch to .use
delete babelEsbuildLoader.loader;
delete babelEsbuildLoader.options;

babelEsbuildLoader.use = [babelLoader, esbuildLoader];

Not sure how the api should look like, just added my own configuration to include styled-components plugin. It seems to work fine after esbuild has done all the heavy work.

Inspiration: https://news.ycombinator.com/item?id=26977799

CRA5 and @craco 6.4.3

How do you guys managed to make it work here #48

i'm trying to upgrade to CRA 5.0 with carco 6.4.3. but it says that there are conflicting dependencies as craco 6.4.3 needs CRA4

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react-scripts
npm ERR! react-scripts@"5.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react-scripts@"^4.0.0" from @craco/[email protected]
npm ERR! node_modules/@craco/craco
npm ERR! dev @craco/craco@"^6.4.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

at the same time if i'm trying to use craco 7.0.0-aplha.3 it complains that carao-esbuild 0.5.0 needs craco ^6.

any advice of what i'm doing wrong is much appreciated as i'm a bit stuck with it for couple of days.

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.