Issue with Static HTML Export in NextJS [duplicate] - reactjs

This question already has answers here:
Error: Image Optimization using Next.js default loader is not compatible with `next export`
(5 answers)
Closed 6 months ago.
I am new in nextJS and trying to deploy project in html.
Develop your app as you normally do with Next.js. Then run:
next build && next export
For that you may want to update the scripts in your package.json like this:
"scripts": {
"build": "next build && next export"
}
And run it with:
npm run build
Then you'll have a static version of your app in the out directory.
above is from https://nextjs.org/docs/advanced-features/static-html-export#how-to-use-it
On npm run build its creating out folder but it have only js files, index.html file is missing.
How to export nextJS project in html.
Thanks
Update
on export i am getting this error
Error: Image Optimization using Next.js' default loader is not compatible with `next export`.
Possible solutions:
- Use `next start` to run a server, which includes the Image Optimization API.
- Use any provider which supports Image Optimization (like Vercel).
- Configure a third-party loader in `next.config.js`.
- Use the `loader` prop for `next/image`.
Read more: https://nextjs.org/docs/messages/export-image-api

replacing Image with img and npm run build. Image optimization not supported next export
<img width={70} height={70} src="https://sun1.beTCOYGm.jpg" alt="мое фото" />

Add the following to module.exports in next.config.js:
experimental: {
images: {
unoptimized: true,
},
},
This turns off image optimization.
Read more here: https://nextjs.org/docs/messages/export-image-api
And here: https://nextjs.org/docs/api-reference/next/image#unoptimized

Related

Nextjs app won't export due to Image Optimization [duplicate]

This question already has answers here:
Error: Image Optimization using Next.js default loader is not compatible with `next export`
(5 answers)
Closed 5 months ago.
I see this question but the most upvoted answer was to use some Akamai-based config and I am not hosting this with Akamai.
I have a React/Nextjs with a package.json whose scripts look like:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"export": "next export"
},
When I run:
npm run export
I get:
> myapp-website#0.1.0 export
> next export
info - using build directory: /Users/myuser/workspace/myappsite/myapp-website/.next
info - Copying "static build" directory
info - No "exportPathMap" found in "/Users/myuser/workspace/myappsite/myapp-website/next.config.js". Generating map from "./pages"
Error: Image Optimization using Next.js' default loader is not compatible with `next export`.
Possible solutions:
- Use `next start` to run a server, which includes the Image Optimization API.
- Configure `images.unoptimized = true` in `next.config.js` to disable the Image Optimization API.
Read more: https://nextjs.org/docs/messages/export-image-api
at /Users/myuser/workspace/myappsite/myapp-website/node_modules/next/dist/export/index.js:149:23
at async Span.traceAsyncFn (/Users/myuser/workspace/myappsite/myapp-website/node_modules/next/dist/trace/trace.js:79:20)
When I check my next.config.js file I see:
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
}
module.exports = nextConfig
What do I need to do so that npm run export runs successfully? And what's happening here?
I also don't understand why Nextjs wouldn't just work as-is, out of the starting gate.
What we have to keep in mind is how Next.js optimization works under the hood. The images are not optimized during build, they are optimized on-demand. Naturally, for that a server needs to be running.
It is mentioned in the docs:
Images can not be optimized at build time using next export, only on-demand. To use next/image with next export, you will need to use a different loader than the default. Read more in the discussion.
Running next export does not run a server. Instead you are trying to export a static HTML out of your next.js project (for example, to run on github pages etc.)
next export allows you to export your Next.js application to static HTML, which can be run standalone without the need of a Node.js server.
There will be unsupported features, and image optimization is one example.
You can change configuration by adding the below to next.config.js:
module.exports = {
images: {
unoptimized: true,
},
}
or
module.exports = {
images: {
loader: 'imgix',
path: 'https://example.com/myaccount/',
},
}
By using the imgix loader, you are offloading that task to imgix
servers, and they will serve you the image. By using unoptimized : true in config, you are disabling image optimization. This way you do not need a server.
In the next.config.js, turn off the image optimization feature, and then run npm build and npm export. Export doesn't support image optimization because there won't be any nextjs server to optimize image. After export you can use third party libraries to optimize your images or load your images from websites which optimizes your images.
Add this is config file -
images: {
unoptimized: true
}

Tailwind not working with NextJS + bun.sh

I am a intermediate level web dev.
I recently heard of BunJS, and now playing around with it.
I am working on NextJS with bun and trying to install Tailwind CSS on it, but seems like Tailwind CSS does not have official instrauction for NextJS powered by bun.
I thought it would be as same as how I install NextJS powered by Node, but looks like it is different from that. I get error whenever I start the app on command line; it tells me to go chack official document, but the doc is taliking about react app rather than next app. The both file structures are very different, so I honestly have no idea what to do to make Tailwind work on NextJS + Bun.sh
If someone knows how to fix this issue, please let me know, thanks for help in advance!
Terminal ↓
[0.07ms] "node_modules.bun" - 58 modules, 6 packages
[2.00ms] bun!! v0.1.6
Link: http://localhost:3000
[0.04ms] "node_modules.server.bun" - 50 modules, 6 packages
[41.51ms] Next.js ready! (powered by bun)
[57.22ms] / - 2 transpiled, 4 imports
warn: To use Tailwind with bun, use the Tailwind CLI and import the processed .css file.
Learn more: https://tailwindcss.com/docs/installation#watching-for-changes
#tailwind base;
^
/home/kawa/Personal_Project/next-app/styles/globals.css:1:1 0
Basically, your project folder does not have a tailwind.config.js file. So, the compiler is looking for the #tailwind directive within globals.css which, of course, doesn't exist. To generate the tailwind.config.js file, first add the tailwindcss package to your project:
bun add -d tailwindcss
Then initialize tailwind css like this
bun run tailwindcss init
This should add the file to your project. Now, if you use the #tailwind, it should work
Running through the tailwind cli docs with bun and nextjs will result in an error like
Specified input file ./src/input.css does not exist.
Instead, point tailwind to the styles/globals.css like:
npx tailwindcss -i ./styles/globals.css -o ./dist/output.css --watch
Then, update your _app.tsx file:
Replace
import "../styles/globals.css";
with
import "../dist/output.css";
and Bob's your uncle (although underlines with text-3x1 are looking a bit wonky)

Material UI withStyles in an NPM package causes errors when used through npm link

I'm trying to locally build the oodt_fm_plugin NPM package and link it locally to the oodt_opsui_sample_app. However, when I'm trying to do that, the following error is thrown in the browser.
Error: Minified React error #321; visit
https://reactjs.org/docs/error-decoder.html?invariant=321 for the full
message or use the non-minified dev environment for full errors and
additional helpful warnings.
The error goes away if I remove the withStyles HOC from the components in oodt_fm_plugin, but I want to preserve it for the material UI styles.
React components in the oodt_fm_plugin have been exported as follows. ( This plugin can be viewed at https://github.com/apache/oodt/tree/development/react-components/oodt_fm_plugin. )
export default withStyles(styles)(Product);
What I tried to overcome this are as follows, but none of those solved the issue.
Making react and react-dom packages in the plugin, dev dependencies
Adding the following snippet to the webpack.config.js of the plugin.
resolve: {
modules: [path.resolve('node_modules'), 'node_modules'],
},
Can someone point me in the right direction so that I can set up both oodt_fm_plugin and oodt_ui_sample_app correctly in local dev environment? Helpful advice is highly appreciated.
Well, I finally managed to solve the problem, after trying for several days. As I found out, it was not a problem with material ui, but with the Create React App. This Github issue comment helped me to solve my problem.
For extra clarity, I will quote the issue comment in this answer itself, so that it will remain here even if the comment gets deleted.
^ Ok, the solution I went for to solve this for create-react-app is to
use react-app-rewired and customize-cra.
Here is my config-overrides.js :
const {
override,
addWebpackAlias, } = require("customize-cra");
const path = require('path');
module.exports = override(
addWebpackAlias({
react: path.resolve('./node_modules/react')
}) )
Example project: https://github.com/dwjohnston/material-ui-hooks-issue/tree/master
Then, modify the start script as follows.
"start": "react-app-rewired start"

create react app - npm run build issues

I am using create-react-app to build an application and when I run npm run build it creates a build folder with static folder inside it which is expected.
build--> static
But when I see the index.html file inside the build folder, the path to assets is /static and not /build/static which is why the page does not load properly as it is missing the assets .
Is there any config setting I can do to fix this problem ?
If all you want is to run your app, all that you have to do is run the command: npm start
But, if you are really trying to prefix the static references to upload your code on an specific subdirectory you should add on your package.json the homepage you want to use on your create-react-app.
So, if you want your react app to use /build in the beginning of each reference you should add the following line to your package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"homepage": "/build",
...
}
The following message is displayed when you generate your build without the homepage in the configurations:
The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:
"homepage" : "http://myname.github.io/myapp",
The build folder is ready to be deployed.
You may serve it with a static server:
yarn global add serve
serve -s build```
But when I see the index.html file inside the build folder, the path to assets is /static and not /build/static
This behaviour is expected.
You're supposed to deploy the build folder and serve the application from it. Since index.html is inside build, it would be served for /, and files in build/static/* will be served for /static/*.
For more specific instructions for this, please read the Deployment section of the User Guide.
It sounds like you're trying to use unimported assets.
I prefer to create an assets folder and place these sort of files here, and then import/use them accordingly.
From the documentation:
import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
If you really want to use the public folder, you can use the PUBLIC_URL variable.
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

Requiring unknown module "crypto" in react-native environment

I'm writing a simple Twitter app using react-native. Using twit module to get twitter feeds and stream. Below is the code, it works fine node. However, when included into my react-native app, seeing error "Requiring unknown module "crypto"". Dependency seems to be myapp->twit->oauth->crypto (thats part of node v0.12.2). Any suggestions to get this working inside react-native environment?
var Twit = require('twit')
var T = new Twit({
consumer_key:''
, consumer_secret:''
, access_token:''
, access_token_secret:''
})
var filtered_tweets=[];
var error;
var isSuccess=false;
function getTweets(searchString){
T.get('search/tweets',{q:searchString, count:100}, getResponse);
}
function getResponse(err,data,response){
if(err) {
handleGetErr(err);
}
handleGetData(data.statuses);
}
function handleGetErr(err){
enter code here
error = err;
}
function handleGetData(data){
data.map(function(tweet){
var twit={
twit:tweet.id,
created_at:tweet.created_at,
text:tweet.text,
retweet_count:tweet.retweet_count,
favorite_count:tweet.favorite_count
};
filtered_tweets.push(twit);
});
console.log(filtered_tweets);
isSuccess=true;
}
getTweets("#sahaswaranamam");
module.exports = getTweets;
![attached][2]
The crypto module is a built-in Node module; React Native runs JS on JavaScriptCore (when on the device or simulator) and on Chrome itself (when using Chrome debugging), so modules that depend on built-in Node.js modules won't work. See the JavaScript Runtime section of the React Native docs for more info.
I'm not sure how hard it would be to integrate into a React Native app, but browser module bundlers like Browserify often have browser versions of core Node.js modules, like this one for crypto.
If you are using rn-nodeify as #emmby suggests, then you can use react-native-crypto. Instructions from the README:
Install
npm i --save react-native-crypto
# install peer deps
npm i --save react-native-randombytes
react-native link react-native-randombytes
# install latest rn-nodeify
npm i --save-dev mvayngrib/rn-nodeify
# install node core shims and recursively hack package.json files
# in ./node_modules to add/update the "browser"/"react-native"
# field with relevant mappings
./node_modules/.bin/rn-nodeify --hack --install
rn-nodeify will create a shim.js in the project root directory
// index.ios.js or index.android.js
// make sure you use `import` and not require!
import './shim.js'
// ...the rest of your code
But rn-nodeify also states:
If you're looking for a saner approach, check out ReactNativify. I haven't tested it myself, but I think philikon will be happy to help
With ReactNativify you create a rn-cli.config.js and then in a transformer.js you let Babel transform bundle dependencies using babel-plugin-rewrite-require:
// The following plugin will rewrite imports. Reimplementations of node
// libraries such as `assert`, `buffer`, etc. will be picked up
// automatically by the React Native packager. All other built-in node
// libraries get rewritten to their browserify counterpart.
[require('babel-plugin-rewrite-require'), {
aliases: {
crypto: 'crypto-browserify',
// ...
},
throwForNonStringLiteral: true,
}]
(Note: You can also do this in without these 2 js files directly in .babelrc)
(Note2: Though ReactNativify is the cleaner way, it is still giving me issues wiring up crypto.getRandomValues for production-use in RN. See this question)
You can use the rn-nodeify module to get crypto on react-native.
Add rn-nodeify to your devDependencies in package.json:
"devDependencies": {
"rn-nodeify": "^6.0.1"
}
Add the following to the scripts section of the same file:
"scripts": {
…
"postinstall": "node_modules/.bin/rn-nodeify --install crypto --hack"
}
Be aware that rn-nodeify will modify your package.json.
More information available here: https://www.npmjs.com/package/rn-nodeify
React Native packager uses Babel under the hood. This means that you can use babel-plugin-rewrite-require Babel plugin to rewrite all require('crypto') calls to require('crypto-browserify'), assuming that the latter is installed in your node_modules.
As of January 2016, you can use .babelrc file to define optional configuration, so this becomes really easy. First, install the dependencies:
npm install --save crypto-browserify
npm install --save-dev babel-plugin-rewrite-require
Then add plugins config to your .babelrc file:
{
"presets": ["react-native"],
"plugins": [
["babel-plugin-rewrite-require", {
"aliases": {
"crypto": "crypto-browserify"
}
}]
]
}
Restart the packager and that should be it.
This is the same approach that ReactNativify uses, except that here we use .babelrc instead of defining custom transformer. When ReactNativify was written, it was not supported, so they had to go with more complex solution. See this file from ReactNativify for almost complete list of node polyfills.
I was having the same issue when implementing the Twilio package in my React Native app, and having React Native break over the crypto dependency.
As a work around I ended up creating a separate, stand alone Node/Express app to act as my server and take care of the Twilio logic I had. That way I removed all Twilio logic from my React Native app and moved it to Node. I then just called my Express route in React Native using fetch, which triggered the functionality I wanted to happen with Twilio. If you're unfamiliar with fetch here's a good starting point -
Making AJAX calls with Fetch in React Native
In addition, here's my question on the crypto dependency breaking my app:
twilio-react-native-unable-to-resolve-module-crypto
As far I can see amazon-cognito-identity-js uses crypto-js 3.3.0 without any additional magic... If that version of the package works then perhaps try that.
After having tried a bunch of these solutions and never really having been satisfied with any of them (some didn't even work), I managed to stumble upon react-native-quick-crypto, which honestly worked much more effortlessly than trying to lift the existing crypto library to the front-end

Resources