Importing and running a standalone React application inside a web component - reactjs

I have a standalone React application that uses webpack for bundling with a requirement of being able to run this bundle within a web component. Can anyone suggest how I should approach this?
I'm thinking something like:
//webpack.config.js
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
library: 'reactUmd',
libraryTarget: 'umd',
umdNamedDefine: true
},
//react-component.js
import '../../packages/react-umd/dist/bundle.js'
class ReactComponent extends HTMLElement {
connectedCallback() {
const mountPoint = document.createElement('span');
this.attachShadow({ mode: 'open' }).appendChild(mountPoint);
reactUmd.renderSomeComponentTo(mountPoint)
}
}
customElements.define('react-component', ReactComponent)
But I'm not sure how I can import the compiled bundle and get a reference to React, ReactDOM, the Main component etc, would exporting as UMD provide the references I need?

So you basically want to access the react component outside the minified bundle file.
Here is one approach:
You tell webpack to create a library for your file. This will basically create a global variable using which you can access all the exported functions from you js entry file.
To do so, add a key called library int your webpack config under output object.
module.exports = {
entry: './main.js',
output: {
library: 'someLibName'
},
...
}
After doing this, restart your webpack server and on console, type window.someLibName. This should print all the methods exported by main.js as an object.
Next step is to create a function which accepts a DOM element and renders the react component on the element. The function would look something like this:
export const renderSomeComponentTo = (mountNode) => {
return ReactDOM.render(<App />,MOUNT_NODE);
}
Now you can access the above function from anywhere in the project, using
const mountNode = document.getElementById('theNodeID');
window.someLibName.renderSomeComponentTo(mountNode);
This way, all the react specific code is abstracted :)
I hope I answered your question. Don't forget to hit star and upvote. Cheers 🍻

Related

SCSS doesn't load on Gatsby

i try to load the SASS for my Gatsby Project but if I check the source code of the web there isn't any classes from my sass.
I am a bit confused and I followed the documentation of Gatsby.
Nothing worked so my last chance is SO.
// gatsby-config.js
plugins: [
'gatsby-plugin-react-helmet',
'gatsby-plugin-fontawesome-css',
'gatsby-plugin-sass',
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'assets',
path: `${__dirname}/static/`,
},
},
]
Here I import the style.
/**
* Add browser relation logic.
*/
require('./style/global.js');
import './style/sass/index.scss';
I followed the gatsby-plugin-sass documentation and I should be all set. After restarting the server and show source-code of my app there is now class name from my sass file.
Best Regards
Knome
I didn't integrate in any component. Because if I see the Source code
of chrome then there should be scss be loaded.
Ok, well... The SCSS is loaded as it should but the styles are not applied to any component because you've not set any class name.
Just do:
const IndexPage =()=>{
return <div className="grid-container">I'm your index page</div>
}
Like any other HTML element.

Webpack mixing up default and named imports

While updating some deps (react-bootstrap) I ran into a react error
You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Compiling the same code with other setups (storybook, create react app, codesandbox, ...) doesn't show the issue.
Looks like the component we import (react-bootstrap/Dropdown), imports another component (react-overlays/Dropdown) which causes the problem.
I tracked the error down to this line which does NOT get outputted:
/* harmony import */ var react_overlays_Dropdown__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_overlays_Dropdown__WEBPACK_IMPORTED_MODULE_4__);
Instead, the non-working code uses the ..._MODULE_4__['default'] syntax, which fails and raises the error.
After hours of searches I found out the problem...
Changing this
module.exports = {
resolve: {
modules: [path.join(__dirname, 'node_modules')]
}
};
to this
module.exports = {
resolve: {
modules: ['node_modules']
}
};
solves the problem.

How export my library with paths using webpack?

Actually my library export the resources to be imported that way:
import { fooComponent } from 'my-library/lib/components'
import { fooHook } from 'my-library/lib/hooks'
What do I need to change in my webpack.config.js to can import my resources that way?
import { fooComponent } from 'my-library/components'
import { fooHook } from 'my-library/hooks'
My webpack.config.js:
...
entry: {
components: './src/components/index.js',
hooks: './src/hooks/index.js',
index: './src/index.js',
services: './src/services/index.js',
templates: './src/templates/index.js'
},
...
output: {
filename: '[name].js',
globalObject: 'typeof self !== "undefined" ? self : this',
library: 'my-library',
libraryTarget: 'umd',
path: path.join(fileRoot, 'lib'),
umdNamedDefine: true
},
Modify path: path.join(fileRoot, 'lib') to path: path.join(fileRoot, '') is not an option, because I need have a distribution path.
Is this possible solve this problem using TypeScript or Webpack?
Firstly, it is not an issue with Webpack. Webpack will bundle everything, according to your config, in ./lib/[name].js, and that is exacly what you want, since you need a distribution path. So Webpack's job ends there.
Enter the role of package.json, which defines which packages are available and where. Let's look into two different codes and what happens under the hood (oversimplification):
import lib from 'my-lib';
look up the script designated in 'node_modules/my-lib/package.json#main`
import all as lib from this script
import { someComponent } from 'my-lib/lib/components';
look up 'node_modules/my-lib/lib/components.js, ornode_modules/my-lib/lib/components/index.js`
import someComponent from this script
So, there doesn't seems to be any possible package configuration that would simply allow you to remove the lib from your imports. But, is it that big of a problem? That's just three letters 😉

ant design - huge imports

I'm using ant design library for my react application.
And I've faced with huge imports, that hurts my bundle (currently 1.1 mb in minified version because of ant-design lib).
How can I differently import antd components through all my app?
UPDATE:
Seems antd has some huge or non optimized modules.
Here the thing - only difference is import Datepicker module, and.. boom! + almost 2MB (in dev bundle ofc.)
UPD: the underlying issue seems to be resolved for the new (4.0) version of antd.
Therefore, if you try to resolve this issue for the earlier versions, the recommended way is to migrate onto antd 4
Previous answer:
At the moment, a huge part of antd dist is SVG icons.
There is no official way to deal with it yet (check the issue on github).
But a workaround exists.
Adapt webpack to resolve icons differently. In your webpack config:
module.exports = {
//...
resolve: {
alias: {
"#ant-design/icons/lib/dist$": path.resolve(__dirname, "./src/icons.js")
}
}
};
Create icons.js in the folder src/ or wherever you want it. Be sure it matches the alias path!
In this file, you define which icons antd should include.
export {
default as DownOutline
} from "#ant-design/icons/lib/outline/DownOutline";
It's also possible to do this with react-app-rewired (create-react-app modifications) within config-overrides.js
1) Prevent antd to load the all moment localization.
Add webpack plugin and configure it in webpack.config.js like the follow:
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /ru/),
],
resolve: {
alias: {moment: `moment/moment.js`}
},
target: `web`
}
2) Use the same moment version as in antd library.
3) Use modularized antd
Use babel-plugin-import
// .babelrc or babel-loader option
{
"plugins": [
["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }]
// `style: true` for less
]
}
I use BundleAnalyzerPlugin to analyze the bundle.
plugins: [new BundleAnalyzerPlugin()]
Looking at the docs
https://ant.design/docs/react/getting-started#Import-on-Demand
there is a recommedation to import individual components on demand.
So, you can try and replace
import { Button} from 'antd'
with
import Button from 'antd/lib/button'
I reduced my bundle size by 500KB by editing config-override.js like so:
config-override.js
const { override, fixBabelImports } = require('customize-cra');
const path = require('path');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css'
}),
// used to minimise bundle size by 500KB
function(config, env) {
const alias = config.resolve.alias || {};
alias['#ant-design/icons/lib/dist$'] = path.resolve(__dirname, './src/icons.js');
config.resolve.alias = alias;
return config;
}
);
./src/icons.js
/**
* List all antd icons you want to use in your source code
*/
export {
default as SearchOutline
} from '#ant-design/icons/lib/outline/SearchOutline';
export {
default as CloseOutline
} from '#ant-design/icons/lib/outline/CloseOutline';
export {
default as QuestionCircleOutline
} from '#ant-design/icons/lib/outline/QuestionCircleOutline';
export {
default as PlayCircleOutline
} from '#ant-design/icons/lib/outline/PlayCircleOutline';
export {
default as PauseCircleOutline
} from '#ant-design/icons/lib/outline/PauseCircleOutline';
export {
default as LoadingOutline
} from '#ant-design/icons/lib/outline/LoadingOutline';
Before
After
Those few components are certainly not 1.2M together. Looks like you are importing the whole library when you only need a few components.
To get antd to load only the needed modules you should use babel-plugin-import. Check your console log for the "You are using a whole package of antd" warning described at that link.
Check out the docs for Create-React-App for how to implement it if you're using CRA.
Try using code splitting using webpack and react router. It will help you to load the modules asynchronously. This is the only solution helped me to improve the page load time when using ant framework.
Issue which caused large bundle size has been fixed in Ant Design 4.0.
Quoting from the release announcement.
Smaller size
In antd # 3.9.0, we introduced the svg icon ([Why use the svg icon?]
()). The icon API
using the string name cannot be loaded on demand, so the svg icon file
is fully introduced, which greatly increases the size of the packaged
product. In 4.0, we adjusted the icon usage API to support tree
shaking, reducing the default package size of Antant by about 150 KB
(Gzipped).
In order to install Ant Design 4 you have to do following
npm install antd#4.0.0-rc.1
// or in yarn
yarn add antd#4.0.0-rc.1

CSS Code Splitting with Webpack 2 and React Router

I'm code splitting my JavaScript files with React Router and Webpack 2 like this:
export default {
path: '/',
component: Container,
indexRoute: {
getComponent(location, cb) {
if (isAuthenticated()) {
redirect();
} else {
System.import('../landing-page/LandingPage')
.then(loadRoute(cb))
.catch(errorLoading);
}
},
},
childRoutes: [
{
path: 'login',
getComponent(location, cb) {
System.import('../login/Login')
.then(loadRoute(cb))
.catch(errorLoading);
},
},
{ /* etc */
}
};
Which results on this bundle:
public/
vendor.bundle.js
bundle.js
0.bundle.js
1.bundle.js
2.bundle.js
Which means that the final user is getting only the JavaScript that he/she needs, according to the route that he/she is in.
The thing is: for the css part, I'm not finding any resource to do same thing, which is to split the CSS according the user's needs.
Is there a way to do it with Webpack 2 and React Router?
Yes, this can be done. You'll need CommonsChunkPlugin in addition to ExtractTextPlugin. Also, define multiple entry points
entry: {
A: "./a",
B: "./b",
C: "./c",
},
and configure ExtractTextPlugin to use entry point names as CSS file names
new ExtractTextPlugin({
filename: "[name].css"
}),
See a full example here:
https://github.com/webpack/webpack/tree/master/examples/multiple-entry-points-commons-chunk-css-bundle
While I may not answer your question how to split css files so that only the necessary ones are loaded the way you want the question to be answered (no plugin or that sort of thing), I hope to give you a possible alternative.
styled-components use the new ES6 feature tagged template literal to style the components inside the javascript file. I think using this library would solve your problem of loading only the necessary css files, because there would be no more css files per se.
react-boilerplate chose styled-components over sass, because
styled-components have a more powerful approach: instead of trying
to give a styling language programmatic abilities, it pulls logic and
configuration out into JS these features belong.
So using styled-components would not only solve your problem of loading only the necessary css, but it would further add to the decoupling of your application, makes it easier to test the design and reason about your app.
Here's the live demo where you can experiment with the styled-components and check how it works.

Resources