Coder Social home page Coder Social logo

callstack / repack Goto Github PK

View Code? Open in Web Editor NEW
1.3K 33.0 99.0 12.99 MB

A Webpack-based toolkit to build your React Native application with full support of Webpack ecosystem.

Home Page: https://re-pack.dev

License: MIT License

JavaScript 21.98% TypeScript 62.06% HTML 0.27% CSS 1.11% Kotlin 3.80% Objective-C 1.12% Objective-C++ 1.93% Ruby 0.57% C 0.10% Swift 1.17% MDX 5.88%
react-native webpack code-splitting module-federation bundler hacktoberfest react typescript

repack's Introduction

A Webpack-based toolkit to build your React Native application with full support of Webpack ecosystem.


Build Status Version MIT License Chat PRs Welcome Code of Conduct Sponsored by Callstack

Re.Pack is a next generation of Haul — a Webpack-based bundler for React Native applications.

Re.Pack uses Webpack 5 and React Native CLI's plugin system to allow you to bundle your application using Webpack and allow to easily switch from Metro.

Check the base webpack.config.cjs or webpack.config.mjs template, if you're curious how it all looks like.

Features

  • Webpack ecosystem, plugins and utilities
  • Build production bundle for iOS, Android and out-of-tree platforms
  • Build development bundle for iOS, Android and out-of-tree platforms
  • Development server with support for:
    • Remote JS debugging
    • Source Map symbolication
    • Hot Module Replacement and React Refresh
    • Reloading application from CLI using r key
  • Built-in Hot Module Replacement + React Refresh support
  • Flipper support:
    • Crash Reporter,
    • Application logs
    • Layout
    • Network
    • Hermes debugger
    • React DevTools
    • Development server (debugging/verbose) logs
  • Hermes support:
    • Running the production/development bundle using Hermes engine
    • Transforming production bundle into bytecode bundle
    • Inspecting running Hermes engine with Flipper
    • ChunksToHermesBytecodePlugin plugin to transform async chunks into Hermes bytecode
  • Code splitting (experimental):
    • Dynamic import() support with and without React.lazy() (recommended).
    • Arbitrary scripts (only for advanced users).
  • REST API for development server:
    • GET /api/platforms - platforms with active compilations.
    • GET /api/:platform/assets - assets emitted from compilation.
    • GET /api/:platform/stats - data about compilation.
  • Module Federation support
  • Code signing and verification
  • @callstack/repack-init - tool that automates the integration of the Re.Pack into React Native projects

Examples

Explore examples of React Native applications using Re.Pack here: https://github.com/callstack/repack-examples.

For a more comprehensive example of a Super App setup with Module Federation please visit our Super App Showcase repository.

Documentation

The documentation is available at: https://re-pack.dev

You can also use the following links to jump to specific topics:

Made with ❤️ at Callstack

@callstack/repack is an open source project and will always remain free to use. If you think it's cool, please star it 🌟. Callstack is a group of React and React Native geeks, contact us at [email protected] if you need any help with these or just want to say hi!

Like the project? ⚛️ Join the team who does amazing stuff for clients and drives React Native Open Source! 🔥

repack's People

Contributors

ambar avatar eps1lon avatar gorbypark avatar grzegorzkruk avatar jaworek avatar jbinda avatar jbroma avatar joe06102 avatar kerm1it avatar lukemorawski avatar meypod avatar mikeduminy avatar niuguohui avatar oblador avatar oferrounds avatar okwasniewski avatar oliverni avatar rafikitiki avatar ramyareye avatar remanation avatar robik avatar roshangm1 avatar scriptedalchemy avatar szymonrybczak avatar thymikee avatar tmaszko avatar tmisiukiewicz avatar vamshi9666 avatar wgtechy avatar zamotany 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

repack's Issues

HMR has some Error!

Environment

  • Android
  • Use TypeScript

Description

image

When I changed App.tsx,the HMR report an error.

Reproducible Demo

RN official demo:

index.js

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

Failed to build bundle due to errors on a clean React Native project

Environment

MacBook Pro 16 2019
npx -v = 7.5.3
XCode = 12.4
cocoapods = 1.10.1
Simulator = iPhone 12 Pro

Description

I set up a react native project by using the npx react-native init AwesomeProject command, and after following the https://github.com/callstack/repack Installation & Setup section guide when I run the npx react-native webpack-start and when the application is started and connected to the server, bundling fails with the following error:

ℹ [12:25:10.889Z][DevServerProxy] Server listening at http://[::]:8081
ℹ [12:27:31.506Z][DevServerProxy] Starting compiler worker { platform: 'ios', port: 49682 }
ℹ [12:27:31.568Z][DevServerProxy] Hermes device connected { deviceId: 0 }
ℹ [12:27:32.748Z][DevServer@ios] Server listening at http://127.0.0.1:49682
ℹ [12:27:32.786Z][webpack-dev-middleware] wait until bundle finished: /index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.AwesomeProject
✖ [12:27:49.611Z][LoggerPlugin] Failed to build bundle due to errors
✖ [12:27:49.611Z][LoggerPlugin] Error in "./node_modules/react-native/Libraries/Utilities/HMRClient.js": Module not found: Error: Can't resolve './getDevServerLocation' in '/Users/duskomirkovic/Documents/Projects/AwesomeProject/node_modules/react-native/Libraries/Utilities'
⠦ Running: (ios) 100%

Reproducible Demo

  1. Ran npx react-native init AwesomeProject
  2. Ran cd AwesomeProject
  3. Ran yarn add -D webpack terser-webpack-plugin babel-loader @callstack/repack
  4. Created react-native.config.js with content specified here: https://github.com/callstack/repack
  5. Created webpack.config.js with content from here: https://github.com/callstack/repack/blob/main/templates/webpack.config.js
  6. Configured XCode build phase Bundle React Native code and images to match the one provided in the Installaton & Setup section here: https://github.com/callstack/repack
  7. Ran cd ios
  8. Ran pod install
  9. Ran cd ..
  10. Ran npx react-native webpack-start
  11. Ran npx react-native run-ios

Default Android configuration fails out of the box

Environment

Tried on both a Pixel 3 XL and a Zebra TC52 (android) device.

"dependencies": {
"react": "17.0.1",
"react-native": "0.64.2"
},
"devDependencies": {
"@babel/core": "^7.12.9",
"@babel/runtime": "^7.12.5",
"@callstack/nativepack": "^1.4.2",
"@react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^26.6.3",
"babel-loader": "^8.2.2",
"eslint": "7.14.0",
"jest": "^26.6.3",
"metro-react-native-babel-preset": "^0.64.0",
"react-test-renderer": "17.0.1",
"terser-webpack-plugin": "^5.1.3",
"webpack": "^5.38.1"
},

node version 15.3.0

Description

If I configure a new project for Windows/Android as described here: https://reactnative.dev/docs/environment-setup

Then make the changes described here:
https://github.com/callstack/nativepack#installation--setup

I paste in the webpack.config.js template from here:
https://github.com/callstack/nativepack/blob/main/templates/webpack.config.js

I can run the bundling server normally and create a bundle without any errors. However, when the app starts, I will receive the following error:

06-04 19:06:02.565  8033 10134 E unknown:ReactNative: Exception in native call from JS
06-04 19:06:02.565  8033 10134 E unknown:ReactNative: com.facebook.react.devsupport.JSException: Unexpected token '='. Expected an opening '(' before a method's parameter list.
06-04 19:06:02.565  8033 10134 E unknown:ReactNative:   at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
06-04 19:06:02.565  8033 10134 E unknown:ReactNative:   at android.os.Handler.handleCallback(Handler.java:938)
06-04 19:06:02.565  8033 10134 E unknown:ReactNative:   at android.os.Handler.dispatchMessage(Handler.java:99)
06-04 19:06:02.565  8033 10134 E unknown:ReactNative:   at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
06-04 19:06:02.565  8033 10134 E unknown:ReactNative:   at android.os.Looper.loop(Looper.java:223)
06-04 19:06:02.565  8033 10134 E unknown:ReactNative:   at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)
06-04 19:06:02.565  8033 10134 E unknown:ReactNative:   at java.lang.Thread.run(Thread.java:923)
06-04 19:06:02.565  8033 10134 E unknown:ReactNative: Caused by: com.facebook.jni.CppException: Unexpected token '='. Expected an opening '(' before a method's parameter list.
06-04 19:06:02.565  8033 10134 E unknown:ReactNative:
06-04 19:06:02.565  8033 10134 E unknown:ReactNative: no stack

If I then put the app into debug mode using the regular devtools menu, it will load fine. I believe this means that the react-native javascript engine is choking on something that Chrome thinks is fine?

Does this mean the babel loader configuration on the default template webpack.config.js is missing some important library? I don't know how to run something like that down or I would try for you.

If I switch to the Hermes engine, the crash is fatal, killing the app and giving no useful (to me) information in the log.

I can run the same app in metro with no problems.

I went through this exercise because the other app I have been developing suddenly developed a fatal (Hermes) crash for no obvious reason. Turns out it was because I turned the devtools debug mode off . In other words, this same exact error. If I change that app from hermes to the default engine, I get the exact error and stack above.

Reproducible Demo

https://github.com/DaveWelling/reproNativePack.git

It looks like you can reproduce this error simply by following the default android configuration instructions (as I did in the repro above) and making sure your devtools debug mode is turned off on your device.

I also ran the repro above on a completely different windows machine this morning and reproduced the problem. I would try it on a Mac or Ubuntu, but I don't have one here at my house.

Assistance Migrating from Haul

Hi All,
Thank you for your work on this library (and Haul)!

I am attempting to transition to this library in an app where we are currently using Haul because of an issue I am having not being able to use flipper (or inspect network requests in Haul's debugger). When I run npx react-native webpack-start, the server starts, but the application errors. I am really struggling to get additional data, but all I can pull up right now is this stack trace which appears to be rooting from my webpack.config.js:

Error loading webpack configuration at "/Users/swoodruff/dev/stormbreaker/apps/plant-floor/webpack.config.js": Error: Cannot find module 'webpack/lib/web/JsonpHelpers'
Require stack:
/Users/swoodruff/dev/stormbreaker/common/temp/node_modules/.pnpm/packages.plexdev.io/react-native-webpack-toolkit/1.0.0_28331a31dd8e7476d616c398e649ea17/node_modules/react-native-webpack-toolkit/dist/webpack/plugins/ReactNativeTarget/ReactNativeChunkLoadingPlugin.js
/Users/swoodruff/dev/stormbreaker/common/temp/node_modules/.pnpm/packages.plexdev.io/react-native-webpack-toolkit/1.0.0_28331a31dd8e7476d616c398e649ea17/node_modules/react-native-webpack-toolkit/dist/webpack/plugins/ReactNativeTarget/ReactNativeTargetPlugin.js

I am using the template webpack.config.js recommended. The only changes I have made were

  1. I uncommented the section alias to ensure all react-native* imports are resolved to the same RN dependency. I am working in a mono repo built with rush, if that helps at all.
  2. Added a fallback for entry to ./index.js.

Any insight or help is really appreciated. I will include any more information that can be of use... I am feeling so lost right now though, I don't have any more to add.

Thank you in advance!

EDIT: Attaching a screenshot to what I believe my issue is. On line 8, it is requiring the file JsonHelpers, but I do not see that file in node_modules/webpack/lib/web.

Screen Shot 2021-03-31 at 11 37 29 AM

DevServer Assets (Images, YAML...etc) Updates

Currently working on a consequent React Native app with the basic Metro Bundler, we commonly use some external assets that are imported as strings with the babel-inline-import-plugin.
Example : import Foo from "./bar.yml".

The main pain point is that for reloading these assets, we regularly need to reset-cache during development stage in order to see these assets been updated in the app which is a time consuming and demotivating process.

Therefore and because of the Metro architecture, I never achieved to hot reload these assets using it. So I thought that by going through other bundler solution approaching the webpack logic like haul or this one, that would solve my issue.
But, after making things works (been able to launch the application through webpack-toolkit with devServer ...etc), this remains the same : I still have to relaunch the bundler (and reset cache if enabled) in order to update these assets.

After trying multiple remediations, the only extensions files that webpack watch/listen about for rebuilding is and always remains code tsx?/jsx? files

Maybe i'm seeing things from a wrong angle, so, if you can bring to me some help concerning this topic, it will be really appreciated.

Thank you in advance

Launch webpack instead of metro during development

Describe the feature

After creating a fresh RN project (RN 0.65.1, TypeScript) & installing repack, running a build in Xcode will still start the Metro packager (instead of Webpack). I solved this by patching packager.sh in react-native/scripts to override the packager command (instead of react-native start, setting PACKAGER_CMD=webpack-start will launch webpack instead), and modifying the "Start Packager" build phase in Xcode as follows:

react-native patch: https://github.com/rahulsmehta/repack-example/blob/master/patches/react-native%2B0.65.1.patch

export RCT_METRO_PORT="${RCT_METRO_PORT:=8081}"
+ export PACKAGER_CMD="webpack-start"

echo "export RCT_METRO_PORT=${RCT_METRO_PORT}" > "${SRCROOT}/../node_modules/react-native/scripts/.packager.env"
if [ -z "${RCT_NO_LAUNCH_PACKAGER+xxx}" ] ; then
  if nc -w 5 -z localhost ${RCT_METRO_PORT} ; then
    if ! curl -s "http://localhost:${RCT_METRO_PORT}/status" | grep -q "packager-status:running" ; then
      echo "Port ${RCT_METRO_PORT} already in use, packager is either not running or not running correctly"
      exit 2
    fi
  else
    open "$SRCROOT/../node_modules/react-native/scripts/launchPackager.command" || echo "Can't start packager automatically"
  fi
fi

(note: this could also be due to error on my part while setting up my example project, so would love any feedback/feel free to close if that's the case)

Motivation

In the interest of making setup easier, it'd be possible to pull the modified versions of launchPackager.command/packager.sh into a scripts/ dir in repack & adding the overrides to the "Start Packager" build phase in the docs. Would there be any interest in accepting a PR for this enhancement?

bug: TesterApp couldn't run , caz of podfile

Environment

host os: macos
react-native: 64.1

Description

Tried to run in ios simulator and build failed with this error message

Invalid `Podfile` file: cannot load such file -- /Users/vamshi/myApps/oss/repack/packages/TesterApp/node_modules/react-native/scripts/react_native_pods.

Reproducible Demo

  1. git clone https://github.com/vamshi9666/repack.git
  2. cd repack/packages/TesterApp
  3. yarn && npx pod-install

Invalid token - see #41

Environment

PNPM monorepo, default webpack.config.js.

Windows 10.

Description

See issue #41.

Works in release and in Chrome debug.

Reproducible Demo

Set up a PNPM monorepo with a react-native package.

Get error when bundling the app

Environment

"dependencies": {
"@callstack/repack": "^2.4.2",
"@react-native-async-storage/async-storage": "^1.15.9",
"react": "17.0.1",
"react-native": "0.64.2"
},
"devDependencies": {
"@babel/core": "^7.12.9",
"@babel/runtime": "^7.12.5",
"@react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^26.6.3",
"babel-loader": "^8.2.3",
"eslint": "7.14.0",
"jest": "^26.6.3",
"metro-react-native-babel-preset": "^0.64.0",
"react-test-renderer": "17.0.1",
"terser-webpack-plugin": "^5.1.3",
"webpack": "^5.50.0"
},

Description

When I run "npx react-native webpack-bundle", I get the error:

error The "path" argument must be of type string. Received undefined
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
at new NodeError (node:internal/errors:329:5)
at validateString (node:internal/validators:129:11)
at Object.isAbsolute (node:path:1070:5)
at Object.getEntry (/Users/mac/Documents/Code/DemoMiniApps/node_modules/@callstack/repack/dist/webpack/utils/env/getEntry.js:29:26)
at Object. (/Users/mac/Documents/Code/DemoMiniApps/webpack.config.js:37:27)
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:996:19)

When I run "PLATFORM=ios npx webpack-cli -c webpack.config.js", I get the error:
Running...[webpack-cli] TypeError: The 'compilation' argument must be an instance of Compilation
at Function.getCompilationHooks (/Users/mac/Documents/Code/DemoMiniApps/node_modules/webpack/lib/NormalModule.js:207:10)
at /Users/mac/Documents/Code/DemoMiniApps/node_modules/webpack/lib/HotModuleReplacementPlugin.js:765:18
at Hook.eval [as call] (eval at create (/Users/mac/.npm/_npx/73f0de3f6fbaf968/node_modules/tapable/lib/HookCodeFactory.js:19:10), :106:1)
at Hook.CALL_DELEGATE [as _call] (/Users/mac/.npm/_npx/73f0de3f6fbaf968/node_modules/tapable/lib/Hook.js:14:14)
at Compiler.newCompilation (/Users/mac/.npm/_npx/73f0de3f6fbaf968/node_modules/webpack/lib/Compiler.js:1053:26)
at /Users/mac/.npm/_npx/73f0de3f6fbaf968/node_modules/webpack/lib/Compiler.js:1097:29
at Hook.eval [as callAsync] (eval at create (/Users/mac/.npm/_npx/73f0de3f6fbaf968/node_modules/tapable/lib/HookCodeFactory.js:33:10), :6:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/mac/.npm/_npx/73f0de3f6fbaf968/node_modules/tapable/lib/Hook.js:18:14)
at Compiler.compile (/Users/mac/.npm/_npx/73f0de3f6fbaf968/node_modules/webpack/lib/Compiler.js:1092:28)
at /Users/mac/.npm/_npx/73f0de3f6fbaf968/node_modules/webpack/lib/Compiler.js:517:12

Error resolving only a subset of scales

Ask your Question

In my project I load image like this
<Image style={styles.emptyIcon} source={require('../../../../images/inbox_nomessage.png')} />

But actually in my project i only have [email protected]
This is just to reduce the assets's size.
This approach works with react-native bundle, but I got error with react-native webpack-bundle because @1x and @2x ones are missing

How to download chunk from server on demand

Ask your Question

I have 2 questions:

  1. When I use ChunkManager.loadChunk('miniapp'),
    I received log: [DevServer@ios] Route GET:/undefined not found.
    Do I have a missing config somewhere?

  2. I understand that I can code a Remote component -> bundle remote chunk has name is remote.chunk.bundle -> upload this chunk to my server -> and in my other project, I can display Remote component without any code related to this Remote component by downloading remote.chunk.bundle via ChunkManager.
    Is my understanding correct?

I had code:

index.js

import { AppRegistry } from 'react-native';
import { ChunkManager } from '@callstack/repack/client';
import AsyncStorage from '@react-native-async-storage/async-storage';
import App from './src';
import { name as appName } from './app.json';

ChunkManager.configure({
    storage: AsyncStorage,
    resolveRemoteChunk: async (chunkId) => {
        return {
            url: `https://dev-api.mydomain.com/students/${chunkId}`,
        };
    },
});

AppRegistry.registerComponent(appName, () => App);

src/index.js

import React from 'react';
import { Text } from 'react-native';

const Remote = React.lazy(
    () => import(/* webpackChunkName: "remote" */ './Remote.js')
);

const App = () => {
    return (
        <React.Suspense fallback={<Text>Loading...</Text>}>
            <Remote />
        </React.Suspense>
    );
}

export default App;

But I get the error: Can't not find module './Remote.js'.

Please help me. Thank you !!!

How can custom middleware be injected?

Ask your Question

If someone wants to use this with the Expo Go app, or a custom dev client, they'll need to inject custom middleware to serve a JSON manifest at /. With Metro, this would look something like:

const { getDefaultConfig } = require("expo/metro-config");
const { getManifestHandler } = require("xdl/build/start/ManifestHandler");
const config = getDefaultConfig(__dirname);

// export EXPO_PACKAGER_PROXY_URL=http://localhost:8081
module.exports = {
  ...config,
  server: {
    ...config.server,
    enhanceMiddleware: (metroMiddleware, server) => {
      const expoMiddleware = getManifestHandler(__dirname);
      return (req, res, next) => {
        if (["/", "/manifest", "/index.exp"].includes(req.url)) {
          return expoMiddleware(req, res, next);
        }
        return metroMiddleware(req, res, next);
      };
    },
  },
};

In Webpack, I'd assume something like this would work:

module.exports = {
  // Default repack config...
  devServer: {
    before(app) {
      app.use((req, res, next) => {
        if (["/", "/manifest", "/index.exp"].includes(req.url)) {
          return expoMiddleware(req, res, next);
        }
        next();
      });
    },
  },
}

But it does not seem to work. Is there some other API to use in order to customize the dev server?

react-native-svg crashing in release in TesterApp

Description

I've had some issues upgrading from 2.0.0 to 2.40 with android release mode specifically and when trying to reproduce it in the tester app I found similar issues, namely the following:

HermesVM: JSI rethrowing JS exception: Cannot read property 'descriptors' of undefined
HermesVM: 
HermesVM: TypeError: Cannot read property 'descriptors' of undefined
HermesVM:     at 72147 (address at index.android.bundle:1:574632)
HermesVM:     at call (native)
HermesVM:     at __webpack_require__ (address at index.android.bundle:1:8502)
HermesVM:     at s (address at index.android.bundle:1:714061)
HermesVM:     at 29896 (address at index.android.bundle:1:617628)
HermesVM:     at call (native)
HermesVM:     at __webpack_require__ (address at index.android.bundle:1:8502)
HermesVM:     at s (address at index.android.bundle:1:714061)
HermesVM:     at 59162 (address at index.android.bundle:1:620839)
HermesVM:     at call (native)
HermesVM:     at __webpack_require__ (address at index.android.bundle:1:8502)
HermesVM:     at s (address at index.android.bundle:1:714061)
HermesVM:     at 66232 (address at index.android.bundle:1:590168)
HermesVM:     at call (native)
HermesVM:     at __webpack_require__ (address at index.android.bundle:1:8502)
HermesVM:     at s (address at index.android.bundle:1:714061)
HermesVM:     at 18918 (address at index.android.bundle:1:33132)
HermesVM:     at call (native)
HermesVM:     at __webpack_requi
AndroidRuntime: FATAL EXCEPTION: mqt_js
AndroidRuntime: Process: com.testerapp, PID: 4878
AndroidRuntime: com.facebook.jni.UnknownCppException: Unknown
AndroidRuntime:  at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
AndroidRuntime:  at android.os.Handler.handleCallback(Handler.java:873)
AndroidRuntime:  at android.os.Handler.dispatchMessage(Handler.java:99)
AndroidRuntime:  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
AndroidRuntime:  at android.os.Looper.loop(Looper.java:193)
AndroidRuntime:  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)
AndroidRuntime:  at java.lang.Thread.run(Thread.java:764)

Through git bisect I tracked it down to being caused by PR #81.

Reproducible Demo

cd packages/TesterApp/android
./gradlew clean
./gradlew assembleRelease
adb install ./app/build/outputs/apk/release/app-release.apk

Failed to load configuration of your project. Cannot find module '@react-native-community/cli/build/commands/start/start'

Environment

System:
    OS: macOS 11.5.2
    CPU: (8) x64 Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
    Memory: 17.30 MB / 8.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 12.22.3 - /usr/local/bin/node
    Yarn: Not Found
    npm: 6.14.13 - /usr/local/bin/npm
    Watchman: Not Found
  Managers:
    CocoaPods: 1.10.1 - /usr/local/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4
    Android SDK:
      API Levels: 28, 29, 30
      Build Tools: 29.0.2, 30.0.3
      System Images: android-30 | Google APIs Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 4.2 AI-202.7660.26.42.7486908
    Xcode: 12.5.1/12E507 - /usr/bin/xcodebuild
  Languages:
    Java: 1.8.0_292 - /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.2 => 17.0.2 
    react-native: 0.65.1 => 0.65.1 
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found
{
  "name": "repacktest",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "17.0.2",
    "react-native": "0.65.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@callstack/repack": "^2.0.0",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "babel-loader": "^8.2.2",
    "eslint": "7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.66.0",
    "react-native-codegen": "^0.0.7",
    "react-test-renderer": "17.0.2",
    "terser-webpack-plugin": "^5.2.2",
    "webpack": "^5.51.2"
  },
  "jest": {
    "preset": "react-native"
  }
}

Description

I've created a new project using npx react-native init command and installed all the necessary libraries. When I try to run webpack it throws an error. Both react-native webpack-start and react-native start fails.

Reproducible Demo

Please checkout to this repo and try to run the project

Enabling Hermes breaks android/iOS builds

Environment

"react": "^17.0.2"
"react-native": "^0.64.2"
"webpack": "^5.44.0"
"@callstack/repack": "^2.0.0-beta.7"

Description

On android, if we enable hermes as seen below, assembling the app fails to execute on task app:bundleReleaseJsAndAssets. However, if we switch back to using the metro bundler, Hermes works fine. We want to keep using repack for the webpack benefits, but also need Hermes for the project.

project.ext.react = [
    entryFile: "index.js",
    enableHermes: true,
    bundleCommand: "webpack-bundle", // removing this line fixes the error
]

Reproducible Demo

  1. Create new react native app
  2. Follow callstack/repack documentation for installation and setup
  3. Copy-paste the webpack config template
  4. Enable Hermes for android build and assemble release build

Errors

iOS

▸ Linking beacon.dev

❌  ld: building for iOS Simulator, but linking in dylib built for iOS, file '/Users/stephenlu/Documents/heroai/frontend/app/ios/Pods/hermes-engine/destroot/Library/Frameworks/iphoneos/hermes.framework/hermes' for architecture arm64

❌  clang: error: linker command failed with exit code 1 (use -v to see invocation)

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening beaconapp.xcworkspace.

** BUILD FAILED **
The following build commands failed:
	PhaseScriptExecution Bundle\ React\ Native\ code\ and\ images /Users/stephenlu/Library/Developer/Xcode/DerivedData/beaconapp-akmcdfwbbupxepbpqfxdjntkinhn/Build/Intermediates.noindex/beaconapp.build/DebugDev-iphoneos/beaconapp.build/Script-00DD1BFF1BD5951E006B06BC.sh
(1 failure)

info Run CLI with --verbose flag for more details.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Android

> Task :app:bundleDevReleaseJsAndAssets FAILED

FAILURE: Build failed with an exception.

* Where:
Script '/Users/stephenlu/Documents/heroai/frontend/app/node_modules/react-native/react.gradle' line: 173

* What went wrong:
Execution failed for task ':app:bundleDevReleaseJsAndAssets'.
> Process 'command '../../node_modules/hermes-engine/osx-bin/hermesc'' finished with non-zero exit value 2

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 32s

Should I need to set the "Debug server host & port for device" on android in or to do Lazy component/bundle loading?

Ask your Question

I have some components lazy loading using react.lazy() and react.Suspense. This works fine in the browser, but when I port the component code to react native and use nativepack/repack on my Android device, it fails with a network error trying to reach localhost/127.0.0.1:54571. Then it follows immediately with an error pointing to the bundle corresponding to the lazy loaded component. That looked suspicious to me so I went to the debug menu for the device application and changed the 'Debug server host & port for device" to be my [dev machine local external IP address]:54571 (e.g. 192.168.12.103:54571).
This worked, but is not documented as a necessary step in the instructions, so I was wondering if that is the intended behavior?

Find and document working SVG loader

Discussed in #58

Originally posted by jaysson July 16, 2021
Do you know any webpack loader for react-native-svg? I was using https://github.com/kristerkari/react-native-svg-transformer with metro. Tried https://www.npmjs.com/package/react-native-svg-loader, but it didn't work. It was published 2 years back, looks like not maintained.

I tried https://www.npmjs.com/package/@svgr/webpack with native: true. That just throws NonErrorEmittedError: (Emitted value instead of an instance of Error) Error in parsing SVG: Non-whitespace before first tag. for all SVGs.

Incorrect `sourceMappingURL` in main chunk production builds

Description

When building a production bundle the path to the sourcemaps added by the SourceMapDevToolPlugin is wrong. For iOS one would expect something like //# sourceMappingURL=main.jsbundle.map but the output is //# sourceMappingURL=index.bundle.map?platform=ios.

Reproducible Demo

cd packages/TesterApp
react-native webpack-bundle --platform ios --entry-file index.js --bundle-output ./dist/main.jsbundle --dev=false
tail dist/main.jsbundle
-> [...] //# sourceMappingURL=index.bundle.map?platform=ios 

Documentation inconsistencies and errors migrating an existing RN app

Environment

I've had the same errors on M1 and intel Macs as well as Windows, on both ios simulators, android emulators, and iOS and android devices. For brevity I will post my latest general info.
OS: Mac 11.5.1 Big Sur, M1 chip
Device: iOS Simulator
Package manager: yarn v1 (no workspaces/symlinks)
Relevant versions:

    "react-native": "0.63.3",
    "@babel/core": "^7.8.4",
    "@babel/runtime": "^7.8.4",
    "@callstack/repack": "^2.0.0-beta.7",
    "babel-loader": "^8.2.2",
    "typescript": "^3.7.5",
    "webpack": "^5.49.0",
    "webpack-cli": "^4.7.2"
    "terser-webpack-plugin": "^5.1.4",

Other info: I'm running all these commands from the VS Code integrated terminal. Never built from XCode/Android Studio.

Description

I've tried setting up both this and Haul a few times and never succeeded. I have an existing react native project that I try to set up repack with. I would just like to verify these are actual mistakes and not issues with my env.

Webpackconfig missing

5. Now you can build your app for production or run development server with `npx react-native webpack-start` and develop your app.

My error:

error Option "--webpackConfig" is missing. Run CLI with --verbose flag for more details.
Error: Option "--webpackConfig" is missing

My webpack.config.js is in the root, next to my package.json and such. Trying to pass the path to it as an argument doesn't seem to do anything.

Issues starting the bundler

* This is the Webpack configuration file for your React Native project.
* It can be used in 2 ways:
* - by running React Native CLI eg: `npx react-native start` or `npx react-native bundle`
* - by running Webpack CLI eg: `npx webpack-cli -c webpack.config.js`

Error 1:

$ webpack-cli -c webpack.config.js
[webpack-cli] Failed to load '/reporoot/rnApp/webpack.config.js' config
[webpack-cli] TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined

Not sure what's up here. I am using the plain template from the repo for the webpack config. More fallbacks need to be set up I guess?

Error 2

Running npx react-native start as the first line suggests just started the metro bundler for me.

Bundler stuck at 10%

So now that I have the bundler running, I connect my iOS emulator and it just seems to get stuck. Stays there forever, or at least for several hours.

ℹ [01:57:50.455Z][DevServerProxy] Hermes device connected { deviceId: 0 } 
ℹ [01:57:51.403Z][DevServer@ios] Server listening at http://127.0.0.1:60608 
ℹ [01:57:51.439Z][webpack-dev-middleware] wait until bundle finished: /index.bundle?platform=ios&dev=true&minify=false 
⠸ Running: (ios) building 10% 

I also had this issue before Hermes was enabled.

Android build fails due to kotlin error in repack

> Task :callstack_repack:compileDebugKotlin FAILED
/node_modules/@callstack/repack/android/src/main/java/com/callstack/nativepack/ChunkManagerModule.kt: (89, 49): Type mismatch: inferred type is String? but String was expected

FAILURE: Build failed with an exception.

I hadn't seen this one before. New issue? My Gradle is 6.2. Build config is debug.

Some relevant looking versions from my gradle files:

        buildToolsVersion = "29.0.2"
        minSdkVersion = 21
        compileSdkVersion = 29
        targetSdkVersion = 29
        supportLibVersion = "28.0.0"
        androidXCore = "1.0.2"
        googlePlayServicesVersion = '16.0.0'
        ext.kotlinVersion = '1.4.10'

        classpath 'com.android.tools.build:gradle:4.0.1'

repack does not start automatally on ios/android build

react-native run ios and react-native run android do not launch repack for me. The metro bundler still launches for me. I did make the native changes, or so I thought. Did I miss something?

Reproducible Demo

Have to go make one still. I don't suppose there's a sample project for repack somewhere?

Support custom webpack watch options/polling

Describe the feature

Support configurable watch options, which would be passed in places like here: https://github.com/callstack/repack/blob/main/packages/repack/src/server/compilerWorker.ts#L10

Motivation

We use Bazel for our monorepo setup, which utilizes symlinks heavily. Webpack file watching does not respond to file changes through symlinks, so we need to use polling for HMR to work correctly. Right now we are patching the package, like so:

-compiler.watch({}, error => {
+compiler.watch({ poll: 500 }, error => {

Would be great if this was supported natively.

Related Issues

unexpected token '='. expected an opening '(' before a method's parameter list

Environment

@callstack/nativepack: "1.4.0"
Android 11.0 emulator
Clean app created with:
npx react-native init MyApp --template react-native-template-typescript

Description

With the default template an error is thrown when the app launches in my android simulator.
"unexpected token '='. expected an opening '(' before a method's parameter list".
The error is actually caused by the nativepack package not being transpiled and it can be solved by letting the babel-loader transpile it.

module: {
  rules: [
  {
    test: /\.[jt]sx?$/,
    include: [
      /node_modules(.*[/\\])+react/,
      /node_modules(.*[/\\])+@react-native/,
      /node_modules(.*[/\\])+@react-navigation/,
      /node_modules(.*[/\\])+@react-native-community/,
      /node_modules(.*[/\\])+@expo/,
      /node_modules(.*[/\\])+pretty-format/,
      /node_modules(.*[/\\])+metro/,
      /node_modules(.*[/\\])+abort-controller/,
      /node_modules(.*[/\\])+@callstack\/nativepack/,
    ],
    use: 'babel-loader',
  },
}

Seeing as nativepack will always need to be transpiled, unless I'm missing something, maybe this should be included in the default template?

I'm new to RN so I could be wrong.

Reproducible Demo

Follow steps in README.
https://github.com/OliverNi/react-native-app-nativepack

Unable to compile Android

[Android][Hermes] NativePack's OKHttp3 Version Causes Runtime Error Making HTTP Calls to LocalHost

Environment

react-native: 0.64.0
nativepack: 1.4.2
android studio 4.1

Description

nativepack Okhttp3 version causes runtime errors

Debugging android using emulator throws JSC and OKHttp Error when making API http network call to localhost

Documentation and default example doesn't include appropriate to configure right build configuration for apps that make api network calls

Reproducible Demo

Setup restify or express node api server and attempt to make an API network call to the node server using react-native fetch APIs

Errors

java.lang.NoSuchMethodError: No virtual method toString(Z)Ljava/lang/String; in class Lokhttp3/Cookie; or its super classes (declaration of 'okhttp3.Cookie'

image

Work Around

Force same version as react-native 0.64.0 in app's app/build.gradle
and include default JS in debug build

image

This is not documented, and I'm not sure of the consequnces

Strict ESM mode supported?

If I set my package.json to have "type": "module" for symlinked dependency it causes the runtime code to fail when trying to load interopRequireDefault and react-refresh because require is not defined. It makes sense to me that require would not be defined in these circumstances, but I cannot figure out how to tell webpack to insert hot module reloading, etc. without using require.

I saw that module.hot is not really allowed with strict ESM mode and that import.meta.webpackHot must be used instead (https://webpack.js.org/api/hot-module-replacement/), but I don't have the faintest idea how to do that. It looks like module.hot is specified all over the place in WebpackHMRClients.ts.

I can get rid of the hot module reloading problems by just disabling HMR, but I don't even know where to start with interopRequireDefault or if there are other things I haven't encountered yet that will be inserted in the code using require.

Unfortunately, if I just turn off strict ESM, then mocha, ava, tape, etc. get really confused as to how to deal with the ESM. I'd have to either use babel just to run my tests (which are completely parseable and very fast in node) or use the standard things/esm module. We have thousands of tests, so parsing them all with babel would be a real perf hit on our builds. The standardthings/esm module is not really well supported at this point and things like optional chaining just won't work.

Updated installation/migration docs

Describe the feature

Complete steps to go from using Metro to using react-native-webpack-toolkit. Should walk through installation, configuration, and starting up a development server.

Motivation

Current installation instructions do not result in a working development environment. Attempting to run yarn react-native webpack-start with the template webpack config complains about missing flags for host, port, projectRoot, watchFolders, assetPlugins, etc.

Related Issues

N/A

React Native Windows: Unhandled 'error' event

Environment

  1. npx react-native --version: 5.0.1-alpha.2
  2. npx react-native info
System:
    OS: Windows 10 10.0.19042
    CPU: (16) x64 AMD Ryzen 7 2700 Eight-Core Processor
    Memory: 6.77 GB / 15.95 GB
  Binaries:
    Node: 14.16.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.5 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.14.12 - C:\Program Files\nodejs\npm.CMD
    Watchman: Not Found
  SDKs:
    Android SDK: Not Found
    Windows SDK:
      AllowDevelopmentWithoutDevLicense: Enabled
      AllowAllTrustedApps: Enabled
      Versions: 10.0.14393.0, 10.0.16299.0, 10.0.17134.0, 10.0.17763.0, 10.0.18362.0, 10.0.19041.0
  IDEs:
    Android Studio: Not Found
    Visual Studio: 16.8.30804.86 (Visual Studio Community 2019), 16.8.30804.86 (Visual Studio Enterprise 2019)
  Languages:
    Java: 14.0.1
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.1 => 17.0.1
    react-native: 0.64.0 => 0.64.0
    react-native-windows: 0.64.3 => 0.64.3
  npmGlobalPackages:
    *react-native*: Not Found

Description

When running npx react-native webpack-start in React Native Windows application, the webpack process crashes with the following error within 30 seconds of running:

⠸ Running: (windows)  100% events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (internal/streams/destroy.js:106:8)

image

Sometimes it crashes after editing a file. But it never runs for more than 1 minute.

Also, possibly related: fast refresh doesn't seem to work, always failing with the following error:

image

What have tried to fix this

  1. Removing node_modules and running yarn
  2. Rebooting the system
  3. Upgrading and downgrading node version
  4. Disabling HMR
  5. Running on a different port (3001)

Reproducible Demo

To reproduce this issue without demo repo, please follow next steps:

  1. npx react-native init demo --template react-native-template-typescript
  2. cd demo
  3. npx react-native-windows-init --version 0.64.3 --language cs --overwrite
  4. npx react-native run-windows
  5. yarn add -D webpack terser-webpack-plugin babel-loader react-native-webpack-toolkit react-refresh
  6. Copy config from the repro repo into the root of the project
  7. npx react-native webpack-start

Repo with the reproducible problem:
https://github.com/br4in3x/rnw-rnwt-problem
To reproduce in the repo, please follow next steps:

  1. yarn
  2. npx react-native run-windows
  3. npx react-native webpack-start

Micro Apps

Can it be used to develop micro apps without dependancies between them, if so how to do so ?

Fast degradation of source map load times

This is probably something I'm doing wrong, but I'm not sure where to start. I hope you don't mind if I run it by you in case you have suggestions on how I might debug.

We have pretty large bundles and I've observed that the source maps seem to load fairly rapidly on the first run. However, it degrades very fast as I add changes and reload the app. Source map loads will usually timeout after the 3rd or 4th reload. If I completely shut down everything (the app on the mobile device and the repack service) and start them again, it seems to help (although I don't know if it is very consistent).
We are using "@callstack/nativepack": "1.4.2",
I don't think I've modifed my sourcemap plugins configuration from that in the template:

        new webpack.SourceMapDevToolPlugin({
            test: /\.(js)?bundle$/,
            exclude: /\.chunk\.(js)?bundle$/,
            filename: sourcemapFilename,
            append: `//# sourceMappingURL=[url]?platform=${platform}`
        }),
        new webpack.SourceMapDevToolPlugin({
            test: /\.(js)?bundle$/,
            include: /\.chunk\.(js)?bundle$/,
            filename: '[file].map',
            append: `//# sourceMappingURL=[url]?platform=${platform}`
        }),

I did try to use the columns: false option on the first constructor above, but that crashed for some reason.

I don't really understand the subtleties between the way repack rebuilds bundles for HMR and just normal bundle rebuilds when you make changes and reload. You may recall I had to disable HMR to get ES6 modules to work. Any chance that is the culprit?
Any suggestions such as a way to increase log verbosity around source map bundling, etc.?
Any chance there is some sort of cumulative caching problem that would affect the source map creation/distribution?

As an alternative, we don't usually get tremendous value from the sourcemaps for vendor code. I started to see if I could somehow speed things up by not including those, but I didn't have a lot of success. Instead of, when an error occurs, delivering me to the nearest location in the code that IS sourcemapped, I believe the debug tools just complained they did not have a sourcemap for the error location. If you know of a way around that problem and think that approach has merit and could wave your hand in the general direction of the best way to do that, I would be super grateful. :)

does it work with react-native-code-push?

Ask your Question

react-native apps allow code-push to upgrade to the latest, because it compares the bundle file, but if it is built with repack, the bundle file will be separated to several files. Does this mean that I can't use code-push with repack?

Unable to resolve ../../Utilities/Platform inside of 'react-native' package

Environment

Description

Unable to resolve modules related to react-native. The app is not able to detect a Platform.js file since Platform.android.js and Platform.ios.js exist but no Platform.js file exists.

Error Message

Error in "./node_modules/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.js": Module not found: Error: Can't resolve '../../Utilities/Platform'

Is there a recommended way to resolve this? Currently have webpack.config.js bootstrapped off of the example.

Originally we had a haul config and things worked. Not sure how to go forwards with this setup.

Error when running from an NPM script

Environment

MacOS 11.4
Node 16.6.1
@callstack/repack: 2.0.0-beta.7
concurrently: 6.2.1

Description

When running the start command npx react-native webpack-start from an npm script with concurrently in my package.json I'm getting the following error :

TypeError: process.stdin.setRawMode is not a function
[1]     at Object.start [as func] (/Users/.../@callstack/repack/dist/commands/start.js:75:19)

My package.json start script :
"dev:ios": "concurrently \"yarn ios\" \"npx react-native webpack-start\""

Reproducible Demo

Setup a basic project following the docs and use my script

ChunkLoadError on Android

Environment

Android 10.
React Natvie 64.2

Description

So my build is finished successfully, the main bundle is generated but somehow the chunk is not getting copied to the APK resulting in ChunkLoadError.

Screen Shot 2021-07-15 at 8 07 25 PM

When I run manually with this command, the chuck is in the correct assets folder.
npx react-native webpack-bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle

Screen Shot 2021-07-15 at 7 54 03 PM

So I suppose the problem is that the bundle is not getting copied by react-native Gradle because the APK doesn't have any of the chunks that they are supposed to have.

Screen Shot 2021-07-15 at 8 05 28 PM

Promise may not be fulfilled with 'undefined' when statusCode is not 204

Environment

react-native 0.64.2
@callstack/repack 2.5.1

Description

I seem to get this error a lot and I'm not sure why, as there's no other information. It only happens when bundling ios, not android. Here's the full console log.

ℹ [21:46:13.025Z][DevServerProxy] Starting compiler worker { platform: 'ios', port: 64743 }
ℹ [21:46:13.074Z][DevServerProxy] Hermes device connected { deviceId: 2 }
ℹ [21:46:14.087Z][DevServer@ios] Server listening at http://[::]:64743
ℹ [21:46:14.088Z][DevServerProxy] fetching from remote server {
  source: 'http://localhost:64743/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=com.coinbase.OnboardingMobile'
}
ℹ [21:46:14.094Z][DevServerProxy] fetching from remote server { source: 'http://localhost:64743/api/dashboard/stats?platform=ios' }
ℹ [21:46:14.129Z][webpack-dev-middleware] wait until bundle finished: /index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=com.coinbase.OnboardingMobile
ℹ [21:46:14.130Z][DevServer@ios] Dashboard client connected { clientId: 'client#0' }
ℹ [21:46:14.132Z][webpack-dev-middleware] wait until bundle finished: /api/dashboard/stats?platform=ios
✖ [21:47:13.971Z][DevServerProxy] Promise may not be fulfilled with 'undefined' when statusCode is not 204 {
  err: {
    type: 'FastifyError',
    message: "Promise may not be fulfilled with 'undefined' when statusCode is not 204",
    stack: "FastifyError: Promise may not be fulfilled with 'undefined' when statusCode is not 204\n" +
      '    at /Users/milesjohnson/Projects/react-native/node_modules/fastify/lib/wrapThenable.js:30:30',
    name: 'FastifyError',
    code: 'FST_ERR_PROMISE_NOT_FULFILLED',
    statusCode: 500
  }
}

Reproducible Demo

How to set root path properly

Ask your Question

Webpack builds successfully, but cannot GET the bundle, because its requesting it from a bad route.
I think its important to mention that I'm using monorepo.
Folder structure:

root/
      packages/
              app1
                     build/platform/index.bundle
                     webpack.config.js
              app2
                     build/platform/index.bundle
                     webpack.config.js

The webpack is trying to get the bundle form the following path:

Fetching from worker {
  url: 'http://localhost:55185/packages/app1index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=app1',
  method: 'GET',
  body: null
} 

Route GET:/packages/app1/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=app1 not found 

When I request http://localhost:55185/index.bundle it resolves correctly.

My question is how can I change /packages/app1/index.bundle to index.bundle when fetching the bundle?

Thanks!

Broken source maps due to `__CHUNKS__` variable insertion

Description

When building a production bundle with repack, the resulting source map output is invalid. We tracked this down to being caused by the __CHUNKS__ code insertion in https://github.com/callstack/repack/blob/main/packages/repack/src/webpack/plugins/OutputPlugin.ts#L165-L172

When commenting it out, the source maps work again. My guess is that the hook compilation.hooks.afterProcessAssets is too late in the process or maybe that the ConcatSource is not the right way to inject it.

Reproducible Demo

cd packages/TesterApp
yarn react-native webpack-bundle --platform ios --entry-file index.js --bundle-output ./dist/main.jsbundle --dev=false
npx source-map-explorer ./dist/main.jsbundle

How to export chunk to server?

Ask your Question

I want to use remote chunk and I need help about export the chunk to server. What file should be upload and how to upload it?
I can't see it in your document. Can you show me the step to do that?
I will appreciate your help.

Thank you

Only works with `chunkIds: 'named'` and `chunkFilename: '[name].chunk.bundle'`

Description

For optimization purposes one might want to use a different value for chunkIds or chunkFilename, but repack makes too many assumptions on the setup instead of using the config values when building the __CHUNKS__ variable and when loading the chunks on the native side.

Reproducible Demo

Change to chunkIds: 'size' or chunkFilename: '[id].chunk.bundle'.

Cannot Parse Compiler Message in terminal output

Ask your Question

Hey, thanks for this amazing project. Webpack is so much more powerful than Metro, so the ability to use it for react-native opens up a lot of exciting possibilities.

I do have a question about terminal output when running the re.pack dev server however:

I'm using the example webpack config and just added a console.log to the top:

console.log('Log entry from webpack config');

However, it ends up in my Terminal looking like this:

✖ [14:31:46.994Z][DevServerProxy] Cannot parse compiler worker message { platform: 'ios', message: 'Log entry from webpack config' }

This is also the case for console output that originates from plugins and other "config-time" elements (e.g. speed-measure-webpack-plugin, etc.).

It's not a deal breaker but I would like to able to make these types of logs a little easier to read.

I see that the docs reference a LoggingPlugin which I suspect I need to configure somehow but I'm not sure how.

`getInitializationEntries` contents causes incorrect `Error` position

Environment

Both iOS and Android, with or without hermes.

Description

When throwing an error inside a repack app (including the TesterApp) the line + column combination is not matching the actual position in the bundle file, therefore the source map lookup ends up on the wrong file/line. The produced source map itself is correct and maps perfectly if getting the position by inspecting the bundle manually or running the bundle via node.

This seems to be caused by the import of react-native package somehow.

Reproducible Demo

Edit TesterApp/index.js to be:

throw new Error('Lol');

and remove ReactNative.getInitializationEntries spread from webpack.config.js and observe that the line+column thrown in RN are correct. Add back ReactNative.getInitializationEntries and see that it doesn't match anymore.

React-native-v8 support?

Ask your Question

I'm using react-native-v8 instead of hermes or jsc. After complete installation guide and run command

react-native webpack-start --verbose

Produces (infinite running):

$ npx react-native webpack-start --verbose
ℹ [12:34:41.725Z][DevServerProxy] Server listening at http://[::]:8081
? [12:34:41.862Z][DevServerProxy] Message client connected { clientId: 'client#0' }
ℹ [12:34:42.340Z][DevServerProxy] Hermes device connected { deviceId: 0 }
? [12:34:58.240Z][DevServerProxy] Message client disconnected { clientId: 'client#0' }
? [12:34:58.276Z][DevServerProxy] Message client connected { clientId: 'client#1' }
? [12:34:58.981Z][DevServerProxy] Message client disconnected { clientId: 'client#1' }
ℹ [12:34:58.983Z][DevServerProxy] Hermes device disconnected { deviceId: 0 }

⠼ Running...

Have support for react-native-v8?

Custom webpack.config.js path broken

Description

Since #80 repack will throw when the CLI runner calculates the default value for the --webpackConfig argument if none of the default locations exists even if the passed argument is valid. Wrapping the default option in a try/catch makes the command work again.

Template to create new apps

Template to create new apps

Is it possible to init a new app with re.pack already configured? if not, do you plan to create a template for that?

Webpack bundle contains DevSettings which crashes on release app on release mode

Environment

System:
OS: macOS 11.3.1
CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Memory: 150.50 MB / 16.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 14.13.0 - ~/.nvm/versions/node/v14.13.0/bin/node
Yarn: 1.22.5 - ~/.yarn/bin/yarn
npm: 6.14.8 - ~/.nvm/versions/node/v14.13.0/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
Managers:
CocoaPods: 1.10.1 - /Users/chakravarthy/.rbenv/shims/pod
SDKs:
iOS SDK:
Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4
Android SDK: Not Found
IDEs:
Android Studio: 4.0 AI-193.6911.18.40.6626763
Xcode: 12.5.1/12E507 - /usr/bin/xcodebuild
Languages:
Java: 15.0.2 - /usr/bin/javac
npmPackages:
@react-native-community/cli: Not Found
react: 17.0.1 => 17.0.1
react-native: 0.64.2 => 0.64.2
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found

Description

I am trying to build a release variant and the app crashes with this error TurboModuleRegistry.getEnforcing(...): 'DevSettings' could not be found.

I am not sure why devsettings is added to webpack bundle

React Native Web

Ask your Question

I have a react native project that support ios and android. it uses react-native-keychain, push-notification and ... .
Now I want to add web support. I followed this steps :

https://medium.com/@aureliomerenda/create-a-native-web-app-with-react-native-web-419acac86b82

but it returns errors like this for several of my modules:

node_modules/react-native-animatable/createAnimatableComponent.js: Support for the experimental syntax 'classProperties' isn't currently enabled (133:24):

then I understand that I must use webpack so follow these steps:

https://callstack.github.io/react-native-paper/using-on-the-web.html

but compiler can not transpile react jsx code in start of my code:

ERROR in ./src/app/index.js 20:6
Module parse failed: Unexpected token (20:6)
You may need an appropriate loader to handle this file type
| render() {
| return (

 <View>

I searched a lot but did not find any solution.

Is this library help me? and how?
Thank you very much in advance.

Can't resolve './getDevServerLocation'

Environment

 webpack 5.50.0,
 @callstack/repack 2.0.0-beta.7,
 iOS: real device iPhone 7,
 react-native:0.64.2

Description

I'm trying to implement repack in a monorepo with hermes.
I have followed the steps in the readme, unfortunately I didn't manage to start the app.
The error I get is :

Failed to build bundle due to errors
Error in "../../node_modules/react-native/Libraries/Utilities/HMRClient.js": Module not found: Error: Can't resolve './getDevServerLocation' in 'path_to_root/node_modules/react-native/Libraries/Utilities'

My monorepo folder structure looks like this:

root/
      packages/
              app1
                     webpack.config.js
              app2
                     webpack.config.js

Since I couldn't find any file that requires ./getDevServerLocation in path_to_root/node_modules/react-native/Libraries/Utilities only in @callstack/repack/dist/client/runtime, I guess its a bug or some paths are not set properly.

My webpack.config.js:

const path = require("path");
const webpack = require("webpack");
const ReactNative = require("@callstack/repack");
const TerserPlugin = require("terser-webpack-plugin");

const mode = ReactNative.getMode();
const dev = mode === "development";
const context = ReactNative.getContext();
const entry = ReactNative.getEntry();
const platform = ReactNative.getPlatform({ fallback: process.env.PLATFORM });
const minimize = ReactNative.isMinimizeEnabled({ fallback: !dev });
const devServer = ReactNative.getDevServerOptions();
const reactNativePath = ReactNative.getReactNativePath({ fallback: "../../node_modules/react-native" });

const babelConfig = {
  presets: ["module:metro-react-native-babel-preset"],
  plugins: ["react-native-reanimated/plugin"],
  env: {
    production: {
      plugins: [
        "transform-remove-console",
        [
          "babel-plugin-jsx-remove-data-test-id",
          {
            attributes: ["testID", "testId"],
          },
        ],
      ],
    },
  },
};

process.env.BABEL_ENV = mode;

/**
 * Webpack configuration.
 */
module.exports = {
  mode,
  devtool: false,
  context,
  entry: [
    ...ReactNative.getInitializationEntries(reactNativePath, {
      hmr: devServer.hmr,
    }),
    entry,
  ],
  resolve: {
    ...ReactNative.getResolveOptions(platform),
    alias: {
      "react-native": reactNativePath,
    },
  },

  output: {
    clean: true,
    path: path.join(__dirname, "build", platform),
    filename: "index.bundle",
    chunkFilename: "[name].chunk.bundle",
    publicPath: ReactNative.getPublicPath(devServer),
  },

  optimization: {
    minimize,
    minimizer: [
      new TerserPlugin({
        test: /\.(js)?bundle(\?.*)?$/i,
        extractComments: false,
      }),
    ],
  },
  module: {
    rules: [
      {
        test: /\.[jt]sx?$/,
        include: [
          /node_modules(.*[/\\])+react/,
          /node_modules(.*[/\\])+@react-native/,
          /node_modules(.*[/\\])+@react-navigation/,
          /node_modules(.*[/\\])+@react-native-community/,
          /node_modules(.*[/\\])+@expo/,
          /node_modules(.*[/\\])+pretty-format/,
          /node_modules(.*[/\\])+metro/,
          /node_modules(.*[/\\])+abort-controller/,
          /node_modules(.*[/\\])+@callstack[/\\]repack/,
        ],
        use: {
          loader: "babel-loader",
          options: babelConfig,
        },
      },
      {
        test: /\.[jt]sx?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            ...babelConfig,
            plugins: devServer.hmr ? ["module:react-refresh/babel", ...babelConfig.plugins] : babelConfig.plugins,
          },
        },
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      __DEV__: JSON.stringify(dev),
    }),
    new ReactNative.AssetsPlugin({
      platform,
      devServerEnabled: devServer.enabled,
    }),
    new ReactNative.TargetPlugin(),
    new ReactNative.OutputPlugin({
      devServerEnabled: devServer.enabled,
    }),
    new ReactNative.DevServerPlugin({
      platform,
      ...devServer,
    }),
    new webpack.SourceMapDevToolPlugin({
      test: /\.(js)?bundle$/,
      exclude: /\.chunk\.(js)?bundle$/,
      filename: "[file].map",
      append: `//# sourceMappingURL=[url]?platform=${platform}`,
    }),
    new webpack.SourceMapDevToolPlugin({
      test: /\.(js)?bundle$/,
      include: /\.chunk\.(js)?bundle$/,
      filename: "[file].map",
      append: `//# sourceMappingURL=[url]?platform=${platform}`,
    }),
    new ReactNative.LoggerPlugin({
      platform,
      devServerEnabled: devServer.enabled,
      output: {
        console: true,
      },
    }),
  ],
};

I have also logged out the variables at the top of the config:

{
  "mode": "development",
  "dev": true,
  "context": "path_to_root/packages/app1",
  "entry": "./index.js",
  "platform": "ios",
  "minimize": false,
  "devServer": { "enabled": true, "hmr": true, "host": "localhost", "port": 52019 },
  "reactNativePath": "path_to_root/node_modules/react-native"
}

Reproducible Demo

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.