Basic implementation of using microbundle not working - reactjs

Please see example repo
https://github.com/inspiraller/webpack-and-microbundle
Microbundle code
mymicrobundle/src/index.js
import React from 'react'
const MyMicroBundle = ({session}) => {
return (
<div>Session = {session}</div>
)
}
export default MyMicroBundle
microbundle/package.json - for output
{
...
"source": "src/index.js",
"main": "dist/index.umd.js",
"module": "dist/index.module.js",
"exports": "dist/index.modern.js",
"unpkg": "dist/index.umd.js"
}
Importing Microbundle code
webpack-loads-microbundle/package.json
{
"dependencies": {
"#mymicrobundle/example": "file:../mymicrobundle",
}
}
webpack-load-microbundle/src/index.tsx
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import MyMicroBundle from '#mymicrobundle/example'
import './index.scss'
const App = () => {
const [session, setSession] = useState('')
return (
<div>
<h1>Hello</h1>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
Note: The microbundle package is bundled as javascript, but I'm using typescript to import it.
Though shouldn't make any difference. I'm also using pnpm instead of npm but also this should be fine as all other imports work.
Something about my path is wrong maybe.
Error
Module not found: Error: Can't resolve '#mymicrobundle/example' in 'C:\baps\react_all\webpack-and-microbundle\webpack-loads-microbundle\src'

webpack resolves modules from its process.cwd()/node_modules by default.
So in your case it is looking for #mymicrobundle/example in webpack-and-microbundle(the current working directory) which is your app directory.
You need to let webpack know, where it needs to search in addition to your project's node_modules.
This can be done using the resolve.modules key. See docs: https://webpack.js.org/configuration/resolve/#resolvemodules
So your webpack config should have something like:
resolve: {
modules: ['node_modules', 'path/to/#mymicrobundle/example'],
},

Related

How to import SVG in ReactJS with craco?

I'm struggling to import SVG's when I'm using craco in my react app.
It's suggested to use #svgr/webpack but I'm not sure how to put it into my craco.config.js
My current setup as per this (I prob shouldn't follow someone's config that doesn't work and expect it to work tho) that does not work:
// craco.config.js
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.paths.json"
}
},
],
webpack: {
configure: (config, { env, paths }) => {
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
return config;
}
}
};
The craco.config.js webpack documentation is here but it's so confusing to me without concrete examples.
Also to note:
Writing import {ReactComponent as mySvg} from "./mySvg.svg" doesn't work because it doesn't recognize it as a ReactComponent.
If I try importing directly via import mySvg from "./mySvg.svg" Typescript doesn't recognize the file.
What I'm currently doing is putting the svg into a React component and using that but it's a nightmare doing that every time. I also put this in #types/custom.d.ts, but it still doesn't work when put into <img src={mySvg} />
// #types/custom.d.ts
declare module "*.svg" {
const content: any;
export default content;
}
import {reactComponent as GoogleLogo} from "../assets/image/googlelogo.svg;
GoogleLogo is component and reactComponent is a required magic string
i find the fix your problem in Adding svgr to create-react-app via craco

Rollup plugin postcss does not inject css imported from node_modules

Here is my rollup config
// rollup.config.js
const postcss = require('rollup-plugin-postcss');
const autoprefixer = require('autoprefixer');
module.exports = {
rollup(config, _options) {
config.plugins.push(
postcss({
plugins: [
autoprefixer(),
],
extensions: ['.css'],
modules: false,
extract: false,
}),
);
return config;
},
};
So if I import css file local from a relative path, it gets injected but I import from node_modules it doesn't
import React from 'react';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
// The following works if I copy the file locally
// import './ReactToastify.css';
What am I doing wrong here?
I came across exactly the same problem and I think I found the solution. The trick here is to use rollup-plugin-postcss (or also rollup-plugin-styles) in combination with #rollup/plugin-node-resolve.
My rollup.config.js looks something like this:
import { nodeResolve } from '#rollup/plugin-node-resolve'
import postcss from 'rollup-plugin-postcss'
// import styles from 'rollup-plugin-styles'
export default {
...
plugins: [
postcss(),
// styles(),
nodeResolve({
extensions: ['.css']
})
]
};
As far as I can tell, for my simple case, it doesn't matter if you use postcss or styles plugins. Both work the same.

Error resolving module specifier: react while doing dynamic import from API

I am trying to dynamically import react component library from API. The js file is fetched succesfully. The babel transpilation has happened successfully too. If I dynamically import the Dummy.js file from localhost like import Dummy from './components/js/Dummy.js', it works. However API import fails with below error. The same error occurs with react lazy too. I basically want to dynamically load the lib and publish events to it. I am newbie to react and front-end development. Please excuse if this is too silly!.
Error resolving module specifier: react
My App.js
import React, { lazy, Suspense } from 'react';
import './App.css';
import ErrorBoundary from './ErrorBoundary';
class App extends React.Component {
render(){
const loader = () => import( /*webpackIgnore: true*/ `https://example.com/Dummy.js`);
const Dummy = ReactDynamicImport({ loader });
const LoadingMessage = () => (
"I'm loading..."
)
return (
<div className="App">
<h1>Simplewidget</h1>
<div id="simplewidget">
<ErrorBoundary>
<Suspense fallback={LoadingMessage}>
<Dummy />
</Suspense>
</ErrorBoundary>
</div>
</div>
);
}
}
export default App;
rollup.config.js, After multiple attempts I arrived at below configuration https://github.com/jaebradley/example-rollup-react-component-npm-package/blob/master/rollup.config.js
// node-resolve will resolve all the node dependencies
import resolve from '#rollup/plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import commonjs from '#rollup/plugin-commonjs';
import filesize from 'rollup-plugin-filesize';
import localResolve from 'rollup-plugin-local-resolve';
export default {
input: 'src/components/js/Dummy.js',
output: {
file: 'dist/Dummy.js',
format: 'es',
globals: {
react: 'React',
'react-dom': 'ReactDOM'
}
},
// All the used libs needs to be here
external: [
'react',
'react-dom'
],
plugins: [
babel({
exclude: 'node_modules/**',
}),
localResolve(),
resolve({
browser: true,
}),
commonjs(),
filesize()
]
}
Dummy.js. I verified in dist/dummy.js that babel transpilation happened correctly. I uploaded the transpiled version to my static hosting site.
import React from "react";
import ReactDOM from "react-dom";
class Dummy extends React.Component {
render() {
return (
<h1>Hello</h1>
);
}
}
export default Dummy;
I have different targets to build, start up my server, create rollup bundle, etc in same app. So, I am pretty confident my rollup doesn't interfere with running the app.
The rollup bundling configuration isn't correct. I was trying to create an es output with commonjs plugin while actually I required an esm module. The error on 'react' is because it is unresolved. Had to make it to use window.React while doing rollup bundle. Also, the App.js should be rolled up as esm bundle to make it dynamically import Dummy.js. In the HTML where app.js's bundle is included, I had to include react and react js umd scripts.
export default {
input: "./src/components/js/Dummy.js",
output: {
file: './dist/Dummy.js',
format: 'esm'
},
plugins: [
babel({
exclude: "node_modules/**"
}),
resolve(),
externalGlobals({
"react": "window.React",
"react-dom": "window.ReactDOM",
})
]
};

React-hot-loader: `hot` could not find the `name` of the the `module` you have provided

I'm using Webpack 4 to create a React project with hooks and I'm trying to get the changes to reload on page live using react-hot-loader following this tutorial.
But I when I try npm start I get following error on the browser:
Error: React-hot-loader: hot could not find the name of the the
module you have provided
This is my App.js contents:
import React from 'react';
import { hot } from 'react-hot-loader';
import Header from './Header';
function App() {
return (
<section className="main">
<Header />
</section>
);
}
export default hot(App);
Alternately I tried importing hot from react-hot-loader/root, but this way I get a different error:
Error: React-Hot-Loader: react-hot-loader/root is not supported on
your system. Please use import {hot} from "react-hot-loader" instead
How could I solve this issue?
You should be requiring it before react:
import { hot } from 'react-hot-loader/root';
import React from 'react';
The package documentation mentions this.
Well, looking at my webpack configs:
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV) }),
],
devServer: {
contentBase: './dist',
hot: true,
},
I had used webpack.HotModuleReplacementPlugin() in plugins and hot: true in devServer which made the second error if I would use react-hot-loader/root.
So removing new webpack.HotModuleReplacementPlugin() from the webpack.config.js, solved my problem.
import { hot } from 'react-hot-loader';
export default hot(module)(App);
or
import { hot } from 'react-hot-loader/root';
export default hot(App);

Conditional Import at build time in react js and react native

I want to share my logic between react js and react native
here is my logic file. it is a HOC that wrap the design component.
I use recompose to create HOCs.
import {compose, withState} from 'recompose';
import FilterOptionsPostsPaginateRelay from './FilterOptionsPostsPaginateRelay';
import handlers from './handlers';
import {withRouter} from "next/router";
export default compose(
withRouter
FilterOptionsPostsPaginateRelay,
withState('loading', 'setLoading', false),
handlers,
)
All of the HOCs are sharable between the react js and react native but the withRouter that comes from next.js router
I want to conditional import {withRouter} from "next/router"; or import {withNavigation} from 'react-navigation'; in my logic file.
I know recompose has branch HOC that I can use but I want the condition checks at build time and prevent extra codes to my bundle and increase performance.
You can create next.config.js to custom webpack config to add alias for router.
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
// Example using webpack option
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//));
config.resolve.alias.router = process.env.IS_REACT_NATIVE ? 'react-navigation' : 'next/dist/client/router.js';
return config
},
};
then in your app, you need to use require to import router
const router = require('router');
const withRouter = router.withRouter || router.withNavigation;
I find a solution using babel-plugin-module-resolver
In web project I added following code to .babelrc
{
"plugins": [
[
"module-resolver",
{
"alias": {
"hybridRouter": "next/router"
}
}
]
]
}
In mobile project I added following code to .babelrc
{
"plugins": [
[
"module-resolver",
{
"alias": {
"hybridRouter": "react-navigation"
}
}
]
]
}
And in my logic files I used this like
import HybridRouter from 'hybridRouter';
Now HybridRouter point to next/router in web project and HybridRouter points to react-navigation in mobile project
You can have conditional imports using the require syntax. There is no need to mess with webpack, if you don't want to. Just do something like this in your case:
let withRouter;
try {
//This is expected to fail if next/router is not available
const router = require("next/router");
withRouter = router.withRouter;
} catch(ex){
const reactNav = require("react-navigation");
withRouter = reactNav.withNavigation;
}
// Use withRouter like you would normally use withRouter from next/router or withNavigation from react-navigation

Resources