Giter Site home page Giter Site logo

thekashey / react-imported-component Goto Github PK

View Code? Open in Web Editor NEW
656.0 12.0 39.0 6.64 MB

βœ‚οΈπŸ“¦Bundler-independent solution for SSR-friendly code-splitting

License: MIT License

JavaScript 5.81% TypeScript 94.02% HTML 0.17%
react ssr webpack code-splitting parcel-bundler server-side-rendering loader async-components

react-imported-component's Introduction

List of all projects

State

React

Code splitting

Node

Data sources

Vue

DOM

Util

Mocking

Styles

Optimizations

Stuff

Rest

Just articles

Habr articles (russian)

react-imported-component's People

Contributors

angryermine avatar dependabot[bot] avatar gabsprates avatar garthenweb avatar greenkeeper[bot] avatar junhyuk-prestolabs avatar lifeiscontent avatar lookfirst avatar midudev avatar nelsieborja avatar tbvjaos510 avatar thekashey avatar unikum-frontend avatar wmertens avatar xiao-hu 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

react-imported-component's Issues

Add a way to block the component in a certain state

I do not know how to do-it myself, I arrived here due to react-loadable not working with react-hot-loader and this tiny component looks awesome and does the job!
The need is to be able to visually test both cases, for the LoadingComponent and the ErrorComponent
Also, it would be interesting if these cases could be delayed, react-loadable has such a facility, do you think it is good idea to have it here too ?

Provide defaults

When I try wrapping the importedComponent() function so it provides a default LoadingComponent, it no longer marks.

Maybe there should be a setDefaults function?

Webpack issue

I have a huge list of components which I would love to use your tool with
I am using ejected "create-react-app
So basically I have a huge menu and want to import components when the user goes to that page

I have

this.components = new Map([
      [
        "Statistic_Report",
        importedComponent(() =>
          import("../Components/Statistic_Report/StatisticReport")
        )
      ],
      [
        "Field_Test/Drive",
        importedComponent(() =>
          import("../Components/Statistic_Report/StatisticReport")
        )
      ],
      [
        "Field_Test/Walk",
        importedComponent(() =>
          import("../Components/Statistic_Report/StatisticReport")
        )
      ]
    ]);

and I get this error

TypeError: Object is not a function. (In 'Object(__WEBPACK_IMPORTED_MODULE_0_react_imported_component__["importedComponent"])', 'Object' is an instance of Object) (attached the image)

screen shot 2018-09-27 at 3 32 27 pm

Also, I tried to use your example

const myImportFunction = () =>
      import("../Components/Statistic_Report/StatisticReport");
    this.NewComponent = importedComponent(myImportFunction);

screen shot 2018-09-27 at 3 36 04 pm

"eager" preloading

One of the disadvantages of the approach taken by this library is a "too late" import. We first have to load everything, and only then, basically just before triggering render, we are triggering the loading of required chunks.

Do we have to do it so late?

  • add one more file "before" index.js
  • rehydrateMarks there, and continue loading
  • and it done "before"

Details

To make it efficient two conditions has to be made

  • a smaller amount of code shall be executed prior rehydrateMarks, so they have to be exported via separate entry point.
  • just after it control should be returned to browser. Promise.resolve().then(() => import(/* webpackMode: eager */"index.js") probably should do the job.
  • it worth to check how webpack runtime chunk might help

An in-range update of react-redux is breaking the build 🚨

The dependency react-redux was updated from 5.0.7 to 5.1.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

react-redux is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

Release Notes for v5.1.0

The biggest fix is for connect() being used with React's newer forwardRef, memo, and lazy APIs.

We also have begun a complete rewrite of our docs for React Redux. Check them out! Many thanks to those who contributed: @markerikson, @sveinpg, @wgao19, @BTMPL, @pyliaorachel, @dagstuan, @Kerumen, and @carloluis (sorry if I forgot someone!). Docs are a great way to get started contributing to open source, so open a PR today! Check #1001 to see what else needs to be done.

We're also looking at overhauling Redux's documentation. Check out reduxjs/redux#2590 for the latest there.

Changes

Commits

The new version differs by 56 commits.

  • b245f83 5.1.0
  • 307f463 Rebuild lock files with npm 6.4.1
  • 1b43eaa (feat): support react 16.6 (#1062)
  • 2093fbb Upgrade to babel@7 (#1043)
  • bc7b6a9 docs: enable search for docusaurus site (#1060)
  • 1e93536 Add nodejs version 10 for ci (#1058)
  • 1ab1596 fix log message hint for ownProps on map function (#1056)
  • 0d9325e Docs/refactor getting started (#1054)
  • ba6b010 Update docs link
  • dde1a0a Clean-Ups after mapState (#1042)
  • 294c42c [Docs] Fix duplicated words in mapState (#1037)
  • 05f943d Fixed broked links in footer (#1041)
  • cde9c04 Fix a very small typo in mapStateToProps docs (#1040)
  • 1db16a4 Fix link to getting started doc (#1039)
  • f930a76 Docs/extracting data with mapstate (#1036)

There are 56 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Webpack issue

Doesn't work with webpack above version 4.28.4 (4.28.4 is fine). I got the following error for the file auto-generated by react-imported-component (.async-imports)

    ERROR in ./front/.async-imports.js 14:56
    Module parse failed: Unexpected token (14:56)
    You may need an appropriate loader to handle this file type.
    | import { assignImportedComponents } from 'react-imported-component';
    | var applicationImports = [function () {
    >   return importedWrapper("imported_-1u8pi01_component", import('./components/AboutPage'));
    | }, function () {
    |   return importedWrapper("imported_-ua8ha3_component", import('./components/AccountActivationPage'));
     @ ./front/app-client.jsx 8:0-26
    
    ERROR in ./front/lib/asyncLoad.js 43:56
    Module parse failed: Unexpected token (43:56)
    You may need an appropriate loader to handle this file type.
    | 
    | export var aboutPage = function aboutPage() {
    >   return importedWrapper("imported_-1u8pi01_component", import('../components/AboutPage'));
    | };
    | export var accountActivationPage = function accountActivationPage() {
     @ ./front/App.jsx 51:0-555 81:67-82 84:15-36 88:15-35 92:15-37 96:15-32 100:15-40 104:15-32 108:15-36 110:15-27 133:35-49 136:21-41 140:21-40 142:21-33 178:21-33 181:35-43 310:15-23 314:15-25 318:15-25 322:15-32 332:15-27 335:15-30 338:15-40 341:15-41 344:15-36 347:15-30 350:15-31 353:15-29 356:15-24 359:15-30 362:15-23 364:15-27
     @ ./front/app-client.jsx

Did I miss any configuration?

PropType forwardProps warning

"react": "^16.5.2",
"react-imported-component": "^5.0.0"

Errors:

Warning: Failed prop type: The prop `forwardProps.isRequired` is marked as required in `ReactImportedComponent`, but its value is `undefined`.
    in ReactImportedComponent (created by ImportedComponent)
    in ImportedComponent (created by ForwardRef)
    in Route (created by Main)
    in Switch (created by Main)
    in div (created by Layout__Content)
    in Layout__Content (created by BaseLayout)
    in div (created by Layout__Container)
    in Layout__Container (created by Layout__ContentContainer)
    in Layout__ContentContainer (created by BaseLayout)
    in BaseLayout (created by BaseView)
    in BaseView (created by Connect(BaseView))
    in Connect(BaseView) (created by Main)
    in main (created by Main)
    in Main
    in Router (created by BrowserRouter)
    in BrowserRouter
    in ThemeProvider
    in AppContainer
    in Provider
Warning: Failed prop type: The prop `forwardProps.isRequired` is marked as required in `UnconnectedReactImportedComponent`, but its value is `undefined`.
    in UnconnectedReactImportedComponent (created by ReactImportedComponent)
    in ReactImportedComponent (created by ImportedComponent)
    in ImportedComponent (created by ForwardRef)
    in Route (created by Main)
    in Switch (created by Main)
    in div (created by Layout__Content)
    in Layout__Content (created by BaseLayout)
    in div (created by Layout__Container)
    in Layout__Container (created by Layout__ContentContainer)
    in Layout__ContentContainer (created by BaseLayout)
    in BaseLayout (created by BaseView)
    in BaseView (created by Connect(BaseView))
    in Connect(BaseView) (created by Main)
    in main (created by Main)
    in Main
    in Router (created by BrowserRouter)
    in BrowserRouter
    in ThemeProvider
    in AppContainer
    in Provider

Cannot use webpack chunks name comment

Hi there,

This issue has hunt me for a long time. Please give me a little bit help.
When I try to use comments in the code to create a webpack chunks name like:

const Login = importedComponent(() => import(/* webpackChunkName: 'LoginContainer' */ './containers/LoginContainer'), { LoadingComponent: LoadingAnimation });

I always get a number for the bundle name instead of LoginContainer. The result as below:
image
If I use system.import instead of import, it will work just fine. All webpack chunk name can be displayed appropriately. The code as below:

const Login = importedComponent(() => system.import(/* webpackChunkName: 'LoginContainer' */ './containers/LoginContainer'), { LoadingComponent: LoadingAnimation });

Here is part of my webpack config: (version is 4.8.3)

output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js',
    chunkFilename: '[name].bundle.js',
    publicPath: '/'
  },

Could someone please give me a little bit hint about where I did wrong? Really appreciate.

what's wrong with my code~~~

i'm sorry to disturb you, i have a question

here is my code

import { AppContainer } from 'react-hot-loader'
import App from './app';


const render = (Component) => (
  ReactDOM.render(
    <AppContainer>
      <Component/>
    </AppContainer>,
    document.getElementById('app')
  )
)

render(App);

if(module.hot){
  module.hot.accept('./app', () => {
    render(App)
  });
}
class App extends React.Component {
  render() {
    return (
      <div>
        <DashBorad />
      </div>
    )
  }
}

and i load asynchronous component , like this

const AsynComp = ImportComponent(() => import('./components/comp'))
const AsynCp1 = ImportComponent(() => import('./components/comp/cp1'))
const AsynCp2 = ImportComponent(() => import('./components/comp/cp2'))
class DashBoard extends React.Component {
  render() {
    return (
      <div>DashBoard <AsynComp /> <AsynCp1 /> <AsynCp2 /></div>
    )
  }
}
class Comp extends React.Component {
  render() {
    return (
      <div>reload</div>
    )
  }
}

export default Comp;

but when i run my code and modify that , show error:

bundle.js:46536 Uncaught ReferenceError: payload is not defined
    at Object.reset (http://localhost:8080/bundle.js:46536:22)
    at http://localhost:8080/bundle.js:46751:33
    at module.exports (http://localhost:8080/bundle.js:5380:25)
    at queue.(anonymous function) (http://localhost:8080/bundle.js:4124:7)
    at Number.run (http://localhost:8080/bundle.js:4110:5)
    at MessagePort.listener (http://localhost:8080/bundle.js:4114:7)

what config parameters i forget??

ps: sorry about my english is bad

drainHydrateMarks() doesn't seem to work when doing server-side rendering using Webpack 4's production mode

I am trying to setup a modern app starter boilerplate and it all looks to work pretty nicely so far. My problem is when I am trying to run the production build (optimized for production using webpack 4)

To reproduce:

  1. Clone https://github.com/Nimaear/react-redux-starter

  2. npm install

  3. npm start
    (You'll see that everything seems to work properly: window.___REACT_DEFERRED_COMPONENT_MARKS is populated and hydrating works good.)

  4. Now build the app for production using npm run build and npm run prod (you'll notice that window.___REACT_DEFERRED_COMPONENT_MARKS is empty now and loading occurs.)

Am I missing something here?

printDrainHydrateMarks() SSR is always an empty array

my relevant package versions

{
   "react": "16.8.6",
   "react-dom": "16.8.6",
  "react-imported-component": "5.5.3",
  "@babel/plugin-syntax-dynamic-import": "7.2.0",
  "parcel-bundler": "1.12.3"
}

"scripts": {
    "generate-imported-components": "imported-components app app/imported.js"
}

server

    let streamUID = 0;

    const app = (
      <ImportedStream takeUID={uid => streamUID = uid}>
        <ApolloProvider client={client}>
          <HelmetProvider context={helmetContext}>
            <StaticRouter location={req.req.originalUrl} context={context}>
              <App />
            </StaticRouter>
          </HelmetProvider>
        </ApolloProvider>
      </ImportedStream>
    );

// then renderToNodeStream(app) etc

client

import './imported' // eslint-disable-line

rehydrateMarks.then(() =>  { ... standard hydrate code ...})

The html is always just <script>window.___REACT_DEFERRED_COMPONENT_MARKS=[];/stream 0/</script>

.babelrc

{
  "env": {
    "client": {
      "plugins": [
        ["react-imported-component/babel"]
      ]
    }
  }

What is __deoptimization_sidEffect__? Possible typo?

Hi! just stumbling through your code to figure out if I like to replace universal component. I am wondering about two things:

  1. What is __deoptimization_sidEffect__ where is this coming from. It seems to be checked for, but is never assigned anywhere. Googling it also did not work. Also seems to be a small typo involved. Shouldn't it be called __deoptimization_sideEffect__?
  2. Is this really in any way specific to React? Wondering about whether it supports other frameworks as well. Even basic things like Preact.

Thanks!

An in-range update of webpack is breaking the build 🚨

The devDependency webpack was updated from 4.22.0 to 4.23.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

webpack is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

Release Notes for v4.23.0

Features

  • add watchMode flag to Compiler to be able to detect watch mode in plugins
  • Prefer chunk names of entrypoints when merging chunks
  • add removedFiles property to Compiler to detect removed files

Bugfixes

  • publish declarations to npm
  • upgrade @webassemblyjs/* for bugfix
  • fix crash when using a side-effect-free wasm module in production mode

Internal changes

  • test on node.js 12
  • fix memory leak in test suite
Commits

The new version differs by 35 commits.

  • a4feb6e 4.23.0
  • 298fa4c Merge pull request #8266 from ljqx/wasm-finalize-exports-fix
  • 035ceb6 force travis rerun
  • 735b4aa Merge pull request #8182 from xtuc/ci-node-nightly
  • 6844c75 add test
  • 8256249 longer timeouts for Compiler test
  • f7ff913 use latest node 12 nightly
  • 1c44f95 fix bug where module is referenced which is not in the graph
  • 98d077d order values with different types correctly
  • f5e45be also export WebAssembly.Global when reexporting globals
  • b22f027 Update tests for new WebAssembly.Global API
  • edcadbb ci: add node 11
  • 91755a2 Merge pull request #8265 from webpack/ci/fix-memory-issue
  • 523ddd7 avoid memory leak
  • 48656d2 [WasmFinalizeExportsPlugin] check if ref is null before using it

There are 35 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Trackable `import`

Even simple, not bound to the components, imports should be trackable.

Server-side rendering components that fetch data asynchronously

I have components that request data from third party endpoints to populate the initial state via ajax.

With the workflow this library provides, how can the server perform these requests when rendering the components server-side then provide that data to the client and prevent an unnecessary AJAX request in the browser?

It's complicated to explain, please let me know if you need more information.

possible bug with compressed class names?

While trying to implement the material-ui library, I notice that SSR renders full css classes, while the client renders uglified classes.

In my fork I have added a demo but for the life of me can't figure out why the router won't reach it. If we can solve that problem first, I can perfect the bug example.

An in-range update of webpack-cli is breaking the build 🚨

The devDependency webpack-cli was updated from 3.2.1 to 3.2.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

webpack-cli is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 88 commits.

There are 88 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Async component will be loaded at the first time

App.jsx

import React, { Component } from 'react';
import Imported from 'react-imported-component'
import './App.css';

const AsyncComponent = Imported(() => import('./AsyncComponent'))

class App extends Component {
  state = {
    show: false
  }
  handleClick() {
    this.setState({show: !this.state.show});
  }
  render() {
    return (
      <div className="App">
        <button onClick={() => this.handleClick()}>switch</button>
        {
          this.state.show && <AsyncComponent />
        }
      </div>
    );
  }
}

export default App;

AsyncComponent.jsx

import React from 'react'

export default () => (
    <div>async</div>
);

output:
f914131c815f2d7339d3a01b8a2f4293

env:

node: 8.10.0
react: 16.3.2
react-imported-component: 4.3.2

It works with 1.0.4

CPU goes high with HMR after update to 2.0.0

I did update to 2.0.0 and now my components don't stop rendering after HMR, I think the connected components are the problem but not very sure.

My Chrome tab gets to 90+% CPU, go back to 1.0.4 solved.

Is it just me?

back slash is not correct in Windows

the command "generate-imported-component" cannot run correctly under Windows, e.g. 5: () => import('..\HomePage'), it should be replaced with slash - 5: () => import('./HomePage').

Warning: Did not expect server HTML to contain a <div> in <div>.

I get this error when I use importedComponent and hydrate() to do SSR hydration. Both the SSR html and hydrated html appear identical and I do not get any error if I import the component normally.

const element = document.getElementById("app");
const app = (
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>
);

// In production, we want to hydrate instead of render
// because of the server-rendering
if (window.___REACT_DEFERRED_COMPONENT_MARKS) {
  // rehydrate the bundle marks
  rehydrateMarks().then(() => {
    ReactDOM.hydrate(app, element);
  });
} else {
  ReactDOM.render(app, element);
}
const Another = importedComponent(() => import("./components/Another"));
// import Another from "./components/Another";

export default function App() {
  return (
    <div>
      <Helmet defaultTitle="Hello World!">
        <meta charSet="utf-8" />
        <link rel="icon" href={favicon} type="image/x-icon" />
      </Helmet>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/another" component={Another} />
        <Redirect to="/" />
      </Switch>
    </div>
  );
}
export default function generateHtml(markup, state) {
  // Get the serer-rendering values for the <head />
  const helmet = Helmet.renderStatic();

  const $template = cheerio.load(HTML_TEMPLATE);
  $template("head").append(
    helmet.title.toString() + helmet.meta.toString() + helmet.link.toString()
  );
  $template("head").append(
    `<script type="text/javascript">window.__PRELOADED_STATE__ = ${JSON.stringify(
      state
    ).replace(/</g, "\\u003c")};</script>`
  );
  $template("head").append(printDrainHydrateMarks());
  $template("#app").html(markup);

  return $template.html();
}

An in-range update of flowgen is breaking the build 🚨

The devDependency flowgen was updated from 1.5.2 to 1.5.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

flowgen is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Strange SSR issue

Hi,

I followed the instructions for SSR (not streaming) in README. I only replaced ReactDOM.render with ReactDOM.hydrate, e.g.,:

  import { rehydrateMarks } from 'react-imported-component';

  // this will trigger all marked imports, and await for competition.
  rehydrateMarks().then(() => {
    ReactDOM.hydrate(<App />,document.getElementById('main'));
  });

I saw a react warning react-dom.development.js:180 Warning: Did not expect server HTML to contain a <div> in <div>. indicating some difference between the client/server side rendering.

So I went ahead and investigate what the difference:

  import { rehydrateMarks } from 'react-imported-component';

  // this will trigger all marked imports, and await for competition.
  rehydrateMarks().then(() => {
    const divMain = document.getElementById('main')
    console.log(divMain.innerHTML); #server side result looks OK
    ReactDOM.hydrate(<App />, divMain);
    console.log(divMain.innerHTML); #async components are not rendered
  });

It turns out that the async components are not rendered. I passed in empty options to importedComponent . The server side generated the marks:
<script>window.___REACT_DEFERRED_COMPONENT_MARKS=["1v1uipo"];/*stream 0*/</script>. If I pass LoadingComponent in the options, then LoadingComponent will be rendered.

Other than this, everything else worked just fine.

Checked the process against README a few times and still couldn't figure out why :(.
Do I need to setoptions.render or use whenComponentsReady?

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The dependency react was updated from 16.5.2 to 16.6.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

props being sent down to child

is there a way to not expose the props of a loadable component to a component?

my example is I've got a bunch of icons and the only props I care about are width/height/fill color and react is complaining about there being extra props on the SVG element that it doesn't know about.

Auto-generate imports list from Babel?

Would it not be possible to automatically update the imported-components.js file that contains all the imports during Babel traversal?

In any case, I had some trouble, it prefixed all node modules with ../. Luckily, since it's just source code I could manually adjust it.

BTW, your project is wonderful 😍 ! It worked as soon as I got the pieces in place. Great approach to the problem IMHO.

Server-side printDrainHydrateMarks returns empty array

Code split works as intended. However, the server-side rendering is not working correctly since its does not fetch any required js chunks
printDrainHydrateMarks returns empty state

<script>window.___REACT_DEFERRED_COMPONENT_MARKS=[]</script>

routes.js

const Home = importedComponent(() => import('./pages/Home'))
const Admin = importedComponent(() => import('./pages/Admin'))
const Blog = importedComponent(() => import('./pages/Blog'))
const Agent = importedComponent(() => import('./pages/Agent'))

generated.js by imported-components

/* eslint-disable */
    import {assignImportedComponents} from 'react-imported-component';
    const applicationImports = {
      0: () => import('../pages/Home'),
      1: () => import('../pages/Admin'),
      2: () => import('../pages/Blog'),
      3: () => import('../pages/Agent'),
    };
    assignImportedComponents(applicationImports);
    export default applicationImports;

.babelrc

{
  "presets": ["react", "es2015" , "stage-2"],
  "plugins": [
    "dynamic-import-node",
    "syntax-dynamic-import",
    ["babel-plugin-webpack-alias", {"config": "/aliases/aliases.config.js"}],
    "transform-decorators-legacy",
    "transform-runtime",
    "react-imported-component/babel"
  ]
}


import './generated.js' // generated import file by  imported-components script
import { rehydrateMarks } from 'react-imported-component';


store.runSaga(rootSaga)
const domRoot = document.getElementById('root')

const renderApp = () => {
return
  rehydrateMarks().then(() => {
    hydrate(
      <Provider store={store}>
        <ConnectedRouter history={history}>
          <AppRoot />
        </ConnectedRouter>
      </Provider>,
      domRoot,
    )
  })
}

renderApp()

server.js

 const history = createHistory({
        initialEntries: [urlPath],
      })
      // const history = createHistory()
      const store = configureStore(history, {
        location: {
            ...
        },
   
      })

      const context = {}
      const htmlRoot = (
        <Provider store={store}>
          <StaticRouter location={urlPath} context={context}>
            <AppRoot />
          </StaticRouter>
        </Provider>
      )

      // pre fetching data from api
      store
        .runSaga(rootSaga)
        .done.then(() => {
  
            const RTS = renderToString(htmlRoot) + printDrainHydrateMarks()
            const head = Helmet.renderStatic() 
            console.log(printDrainHydrateMarks())

            res.status(code).send(renderDom(RTS, port, host, storeState, head))
          }
        })
        .catch(e => {
          console.log(e.message)
          res.status(500).send(e.message)
        })

      renderToString(htmlRoot)
      console.log(printDrainHydrateMarks())

      store.close()
    } else {
      res.status(500).send(_err)
    }m

An in-range update of enzyme is breaking the build 🚨

There have been updates to the enzyme monorepo:

    • The devDependency enzyme was updated from 3.7.0 to 3.8.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the enzyme group definition.

enzyme is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Pre-load webpack chunks via initial html

Right now, the hydration waits for the components to be loaded, which fires off the requests for the required JS files.

However, this means that those files are only requested once all the initial JS was downloaded and parsed. It would be nice if the required JS files are already marked in the initial HTML.

To do so, the marks array has to be converted to a list of client JS files on the server, and then added as <script src/> tags.

I think a possible approach would be to use a regex to scan all client JS files at server start, so that it is independent of the used bundler or chunking. It only needs to make sure it's scanning JS files from the current build (use an assets array), and the regex should only match the definition of the components, not the imports of the components.

An in-range update of eslint-plugin-react is breaking the build 🚨

The devDependency eslint-plugin-react was updated from 7.11.1 to 7.12.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

Release Notes for v7.12.0

Added

Fixed

Changed

Commits

The new version differs by 127 commits.

  • a83d65c Update CHANGELOG and bump version
  • 0c6160e [Dev Deps] update coveralls, babel-eslint, typescript
  • cd6c8e6 [Deps] update resolve
  • d2b5b73 Merge pull request #1828 from alexzherdev/1721-no-typos-create-class
  • e747459 [Tests] remove node 5/7/9, add node 11
  • b33ae84 Merge pull request #1098 from arian/createElement-display-test
  • 84be80a Merge pull request #1824 from alexzherdev/1762-jsx-max-depth-false-positive
  • a442067 Merge pull request #2029 from sstern6/issue1422
  • 7d07c37 Merge pull request #2032 from alexzherdev/jsx-fragments-message
  • 8c6a8e2 Merge pull request #2089 from jomasti/feature/support-react-forwardref-memo
  • 14451d4 Merge pull request #2085 from himynameisdave/issues/2083
  • 8be52c7 πŸ“ Addresses CR comments
  • f7e3121 Merge branch 'master' of https://github.com/yannickcr/eslint-plugin-react into issues/2083
  • 77e3fd0 Merge pull request #2090 from JBallin/no-method-set-state-docs-url
  • 7da9e0d Fix noMethodSetState docsUrl's

There are 127 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

babel-preset-latest deprecated

babel-preset-latest is deprecated in favor of babel-preset-env. It is throwing errors for me, and likely others, so should move .babelrc to

{
  "presets": ["env","react"],
  "plugins": ["transform-class-properties","dynamic-import-node"]
}

and package.json to:

    "babel-preset-env": "^6.24.1",

Usage when React is embeded into server-side app

Hi,

I've an application running on http://myapp.local - and it's a Django based. On one of it's pages I'm using a React component with simple piece of code

<div id="root"></div>
<script src="http://localhost:3000/static/js/bundle.js"></script>
<script src="http://localhost:3000/static/js/main.chunk.js"></script>

and devserver running on http://localhost:3000

My component is getting quite big and I'm trying to split the code so I've added

import importedComponent from 'react-imported-component';
const SomeComponent = importedComponent( () => import('./SomeComponent'))

It compiles fine but it tries to load chunk from http://myapp.local/static/js/1.chunk.js instead of using localhost:3000. Is there any way to configure this, force hostname or something like that ?

SSR not work when to execute JS using PhpExecJs

Hello everyone, I very apologize if my question is too stupid. I followed the instructions in Readme, but my server.js is being executed from PHP by PhpExecJs, so 'detect-node' does not detect the environment as 'server side'. Could this be the reason that SSR is not working? Thank you!

An in-range update of enzyme is breaking the build 🚨

There have been updates to the enzyme monorepo:

    • The devDependency enzyme was updated from 3.7.0 to 3.8.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the enzyme group definition.

enzyme is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Cooperation with lazy/Suspense

I'm wondering if there is a way to use Suspense and lazy on the browser side in some way together with react-imported-component. Are all the functionalities overlapping, or is RIC basically what l+S will be later when it supports SSR?

What will be the future of RIC and l+S?

Imports Map

Look like CSR only customers could use hash-based route predictions to load nested chunks prior to the normal behaviour (>1 loading wave).

Expected results: CSR only applications ("SPA"s) might have the same "good" code-splitting experience, as SSR ones have.

  • extract webpack-chunks from the code
  • provide API to load any chunk
  • provide a way (react snap?) to crawl used imports in the application
  • provide a way to test the mapping for corectness

An in-range update of react-imported-component is breaking the build 🚨

The dependency react-imported-component was updated from 5.0.1 to 5.1.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

react-imported-component is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 8 commits.

  • c222653 5.1.0
  • db883e8 add size-limit 3.5kb
  • 71d9fba document suspense support
  • 94a37b5 Merge pull request #33 from theKashey/greenkeeper/default/react-imported-component-5.0.1
  • 8d4eaab chore(package): update lockfile examples/SSR/parcel-react-ssr/yarn.lock
  • 38d56a2 chore(package): update lockfile examples/SSR/typescript-react/yarn.lock
  • bb48a49 fix(package): update react-imported-component to version 5.0.1
  • bfaa311 fix(package): update react-imported-component to version 5.0.1

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Is the Async SSR (renderToStream) part of the readme up to date?

Hi,

I'm a bit confused by this part of the readme/doc. Could this snippet:

import {ImportedStream, drainHydrateMarks} from 'react-imported-component';

let streamUID = 0;
const html = renderToString(
  <ImportedStream takeUID={uid => streamUID=uid}>
    <YourApp />
  </ImportedStream>) + printDrainHydrateMarks(streamUID);

be

import {ImportedStream, printDrainHydrateMarks} from 'react-imported-component';
import { renderToNodeStream } from 'react-dom/server';

let streamUID = 0;
const html = renderToNodeStream(
  <ImportedStream takeUID={uid => streamUID=uid}>
    <YourApp />
  </ImportedStream>) + printDrainHydrateMarks(streamUID);

? Or maybe I'm just missing something.
Thanks for you help.

An in-range update of @types/react is breaking the build 🚨

The dependency @types/react was updated from 16.8.1 to 16.8.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Trouble getting it to work

Hi and thanks so much for this plugin.

Sorry to bother but I can't get it to work in production. I seem to miss something obvious and the problem may very much be rooted in my config.

I'm doing something like this:

const Foo = importedComponent(
  () =>
  import( /* webpackChunkName:'Foo' */ './Foo')
)

class App extends Component {
  render() {
    return (
      <Foo />
    )
  }
}

export default App

In development SSR and client side seem to work perfectly. But when I deploy the app I get an error that I could trace back to the RegEx matching in importMatch.

In your test case the RegEx

/\(['"]imported-component['"],\s?['"](.*),/

matches correctly

`() => importedWrapper('imported-component', 'mark1', __webpack_require__.e(/*! import() */ 0).then(__webpack_require__.bind(null, /*! ./components/Another */ "./app/components/Another.tsx")))`

But when I inspect my code, what's getting matched against the RegEx is

`function(){return e="imported-component",t="-1g25iq8",r=Promise.resolve().then(function(){return n(481)}),"undefined"!=typeof __deoptimization_sideEffect__&&__deoptimization_sideEffect__(e,t,r),r;var e,t,r}`

It seems to me that Webpack is not picking up the import? The relevant bit of the config looks like this:

    rules: [
      {
        test: /\.(j|t)sx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              babelrc: false,
              comments: true,
              presets: [
                '@babel/react',
                [
                  '@babel/preset-typescript',
                  {
                    isTSX: true,
                    allExtensions: true,
                  },
                ],
                [
                  '@babel/env',
                  {
                    targets: {
                      edge: '17',
                      ie: '11',
                    },
                    useBuiltIns: 'usage',
                    modules: false,
                  },
                ],
              ],
              plugins: [
                'transform-class-properties',
                'react-hot-loader/babel',
                'react-imported-component/babel',
              ],
            },
          },
        ],

Do you have any clue what I might be missing? Any hint would be appreciated. :-)

An in-range update of enzyme is breaking the build 🚨

There have been updates to the enzyme monorepo:

    • The devDependency enzyme was updated from 3.7.0 to 3.8.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the enzyme group definition.

enzyme is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

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.