NextJS image module not found - next.js

Im new to NextJS. Im very confused about images. I get the below error. I followed the documentation for the npm next-image but I still cant display the image
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
const withImages = require('next-images')
module.exports = withImages({
webpack(config, options) {
return config
}
})

check your next version in package.json, if it is more than 10, you don't need any third-party libraries

I had to make sure to create a file called next.config.js in the root project directory. and place this inside
const withImages = require('next-images')
module.exports = withImages();

Related

Unable to fetch excel file in production in nextjs

I have an excel file named Words.xlsx in public directory. Initially, during development mode, setting file path to /public/Words.xlsx worked fine but it failed in production mode saying that it can't read file path. Then, I read this and changed path to/Words.xlsx but I am still receiving the same error(below) in my function logs of vercel.
[Error: ENOENT: no such file or directory, open '/Words.xlsx'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/Words.xlsx'
}
ENOENT: no such file or directory, open '/Words.xlsx'
Further, I am using this npm package to read excel file. Below is the code of how I use it:
const res1Sheet = await readXlsxFile('/Words.xlsx', { sheet: 1 });
How do I solve this?
Checking documentation, found this. Hopefully it might help someone who comes here one day.
Note: Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available. We recommend using a third party service like AWS S3 for persistent file storage.
give full path such as public/Words.xlsx
Refer this documentation: https://docs.sheetjs.com/docs/demos/content#nextjs
you can use this sysntax:
const res1Sheet = await readXlsxFile('public/Words.xlsx', { sheet: 1 });

#Babylonjs (ES6) in Nextjs failes with unexpected token 'export'

I'm building my website with Nextjs and importing Bablyonjs was throwing up the following error.
syntaxError: Unexpected token 'export'
module.exports = require("#babylonjs/core")
I'm using the standard nextjs setup with tsconfig.json
I'm refering to this Babylon documentation and using the examples verbatim.
https://doc.babylonjs.com/extensions/Babylon.js+ExternalLibraries/BabylonJS_and_ReactJS
https://doc.babylonjs.com/divingDeeper/developWithBjs/treeShaking
After a not so insignificant amount of time searching i finally learned the following.
#babylon (es6) is not compiled into javascript and is instead nicely defined (es6) typescript friendly library of source code. (helps when wanting to treeshake)
Nextjs out of the box isn't configured to compile anything in node_modules. It expects precompiled javascript ready to consume.
Point 2. is why i received the error, nextjs was expecting compiled js and it was getting uncompiled source.
To fix this you need to add a next.config.js and configure it with next-transpile-modules and next-compose-plugins.
yarn add next-transpile-modules
yarn add next-compose-plugins
next.config.js
//const withTM = require('next-transpile-modules')(['#babylonjs']);
const withTM = require('next-transpile-modules')(['#babylonjs/core']); // As per comment.
const withPlugins = require('next-compose-plugins');
const nextConfig = {
target: 'serverless',
webpack: function (config) {
/// below is not required for the problem described. Just for reference.(es6)
config.module.rules.push({test: /\.yml$/, use: 'raw-loader'})
return config
}
}
module.exports = withPlugins([withTM], nextConfig);
It compiled without error after this.
References
Handy links i came across solving this issue.
https://github.com/vercel/next.js/issues/706
https://www.npmjs.com/package/next-transpile-modules
https://www.npmjs.com/package/next-compose-plugins
https://www.typescriptlang.org/tsconfig
https://doc.babylonjs.com/divingDeeper/developWithBjs/treeShaking
https://doc.babylonjs.com/extensions/Babylon.js+ExternalLibraries/BabylonJS_and_ReactJS
Links that helped some on the way to understanding the problem.
Test ES6 modules with Jest
https://forum.babylonjs.com/t/jest-is-crashing/12557/7
https://github.com/MichalLytek/type-graphql/issues/689
For Next.js 11, I had to slightly revise the answer from Emile:
Install the following package:
yarn add next-transpile-modules
In your next.config.js file add the following:
const withTM = require('next-transpile-modules')(["package2", "package2"]);
module.exports = withTM({
reactStrictMode: true
})
Put assets folder inside public folder. To access assets can be done by calling full path url.
await SceneLoader.Append(
'http://localhost:3000/assets/characters/avatar.glb'
);

Next JS: Module parse failed: Unexpected character '�' (1:0)

Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently, no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
Error while importing image.
Does anyone know why this is happening?
I am using nextjs
In next.config.js import next-images
const withImages = require('next-images')
and in module.exports use it like
module.exports = withImages({ ...//your content here })
for people having the problem #Prabhu answer is correct but you can use it like this with out giving content.
it worked for me with this error on .png image
Install: npm install next-images
in root dir => next.config.js
const withImages = require("next-images");
module.exports = withImages();

Firebase Hosting: Function not working with ServerMiddleware (Vue/ Nuxt)

I am building a project that utilises ServerMiddleware to render some pages client side only (I can't find another way of getting this working well without ServerMiddleware. Problems on refreshing pages and so on...)
The problem: Unfortunately every time I try and deploy to my Firebase Function through 'firebase deploy' I get an error:
Error: Cannot find module '~/serverMiddleware/selectiveSSR.js'
The function builds OK if I exclude the following line. Nuxt/ Vue is not including ~/serverMiddleware/ as part of its build as far as I can see.
Here is the code in nuxt.config.js to reference my serverMiddleware:
serverMiddleware: ['~/serverMiddleware/selectiveSSR.js']
Adding either the directory or path (as above) to the file itself within Build in nuxt.config.js does not help either. Maybe I am doing it wrong?
Everything works perfectly when testing (Not building) locally.
Any ideas on how I can resolve this please?
Thanks!
Ok so for anyone else who hits this, here is how I got around it.
Firstly, I don't know if this is the fault of Firebase Hosting or Nuxt (I would guess Nuxt but I stand to be corrected), but here is what to do....
1) Remove any reference to ServerMiddleware from nuxt.config.js
2) Add the following to nuxt.config.js
modules: [
'~/local-modules/your-module-name'
],
3) Create directory ~/local-modules/your-module-name in your project root
4) In the new directory, create a package.json:
{
"name": "your-module-name",
"version": "1.0.0"
}
and index.js - key thing, this.addServerMiddleware allows you to call middleware server-side
module.exports = function(moduleOptions) {
this.addServerMiddleware('~/serverMiddleware/')
}
5) Create directory ~/serverMiddleware
6) Add your middleware function to index.js in the new directory:
export default function(req, res, next) {
// YOUR CODE
next() // Always end with next()!
}
7) Update package.json with your new local module under "dependencies":
"your-module-name": "file:./local-modules/your-module-name"
Don't forget you need to do this within the functions directory too or Firebase will complain it can't find your new module

Is there any way to tell angular-cli (for angular 2) to generate minified version of css?

As the title says, when I run "ng serve" angular-cli generates normal css whereas I expect to get the minified version.
Is there any specific setting to use for angular-cli-build, or some additional plugin to install and use?
This is my angular-cli-build.js
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/**/*.+(js|js.map)',
'es6-shim/es6-shim.js',
'reflect-metadata/**/*.+(ts|js|js.map)',
'rxjs/**/*.+(js|js.map)',
'#angular/**/*.+(js|js.map)',
'angular2-cookie/**/*.js'
]
});
};
ng build --prod --env=prod
or
ng serve --prod
Will minify and add a file hash for you.
the --prod tells it to minify hash, and gzip.
the --env=prod tells it to use your prod environment constants file.
which would look like this
You can use
# --env=<your_env>
# --no-sourcemap
# minify => ./minify.js
ng build --env=prod --no-sourcemap && node minify
minify.js
// npm i --save-dev minifier fs-jetpack
const jetpack = require('fs-jetpack');
const path = require('path');
const minifier = require('minifier');
const files = jetpack.list(path.join(__dirname, 'dist'));
console.log(files);
for (const file of files) {
if (/.*(\.js|\.css)$/g.test(file)) {
console.log(`Start ${file}`);
const filePath = path.join(__dirname, 'dist', file);
minifier.minify(filePath, {output: filePath});
}
}
console.log('End');
James' commands DO work and DO minify even when using ng serve --prod.
However you may see something like the following in Chrome and get confused:
That doesn't look minified does it!
Look more carefully and you'll see js:formatted indicating that the pretty print feature was enabled.
Opening the URL http://localhost:4200/main.5082a3da36a8d45dfa42.js directly in a new tab showed me that the CLI was indeed minifying it fully.
You can click the {} icon to turn this feature off, but it seems to like to disappear once the code has been pretty printed so you may need to reload the page and click it quickly.
In 2020 it is just enough to use --prod flag, when building project:
ng build --prod

Resources