Error: Can't resolve './images/sample.png' React Webpack - javascript

Been trying to build a MERN app with Webpack, and can't seem to load any images in React.
React component render method:
const logo = require('./images/sample.png');
<img src={logo}'/>
Webpack
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: ['babel-loader'] },
{ test: /\.css$/, use: ['style-loader','css-loader']},
{test: /\.(jpg|png|svg)$/, loader: 'url-loader'}
] }
ouputs bundle.js into src folder, file structure below
File structure
app
|......src
.........|components
....................|component.js
.........|images
....................|sample.png
It doesn't matter how I change the path in require, and even if I put the sample.png image in the same folder as component.js I get the error that it can't be resolved. I'm thinking it must be a webpack error, but no matter how many tutorials and forums I read I can't fix it.
Ideally I would dynamically load images rather than declaring specific requires like this, so if theres a better way please tell me.
UPDATE:
I changed src={logo} to src={require("${logo}")}, and no longer get a server-side error. Instead, I get an error in the developer console (using Chrome) that seems to be returning the img URI (react problem?):
Uncaught Error: Cannot find module 'data:image/png;base64...'

In your web.config.js you need
const imageLoaderConfiguration = {
test: /\.(gif|jpe?g|png|svg)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
};
and add it here
module: {
rules: [
...
imageLoaderConfiguration,
...
],
},

Related

How do I resolve the "Module not found: Can't resolve [css file] in [directory]" when deploying next.js site to Netlify?

I am trying to deploy this site to netlify: https://github.com/Koda-Pig/joshkoter.com
But I am getting this error:
10:02:31 AM: Module not found: Can't resolve '../styles/home.module.css' in '/opt/build/repo/pages'
10:02:31 AM: > Build failed because of webpack errors
My next.config.json file looks like this:
module.exports = {
reactStrictMode: true
}
const withVideos = require('next-videos')
module.exports = withVideos()
According to Next.js website, there is built-in support for CSS modules, and Netlify doesn't seem to have a problem with any of the other CSS modules I've created, so I don't understand why there is a a webpack error.
I have tried specifying a CSS loader in next.config.js like this:
module.exports = {
reactStrictMode: true,
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
}
const withVideos = require('next-videos')
module.exports = withVideos()
I also tried with this config:
module.exports = {
reactStrictMode: true,
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
}
const withVideos = require('next-videos')
module.exports = withVideos()
But I got the same error message. This is my first time deploying a next.js site to Netlify, so forgive me if I am missing something obvious.
Any help would be greatly appreciated.
Changing your .css file name might fix your problem.
It seems like a file name problem, I got the same error and fixed it by doing following changes.
I used construction.js and imported Construction.module.css in styles folder.
I changed name from Construction.module.css to ConstructPage.module.css and formated all the .css file.
Therefore it worked for me and I fixed the problem.
Hope it will work for you too.

I am having a problem building my Node app with webpack

Let me describe my problem. I have developed a Node.js application with ES6, it is a REST API using several Node modules especially from google-cloud because I am using Google Cloud Vision and Translate APIs.
Until now there is no problem, everything works as expected, but things got wrong when I wanted to run it as a service on a Windows Server. I found a way to do it here using the Node module "node-windows".
I made the service script like in that post and the service got installed and shown in the Windows services list, but when I click to start it stops immediately.
After some analyzing I remembered that I am using ES6 that needs to be transpiled to ES5 to work like a standard Node script, so I thought that building my whole app with webpack will solve that for me, but not exactly, I got my bundle.js generated with webpack without any error (just some warnings), then when I try to run it with node ./bundle.js it returns errors like :
Error: The include '/protos/google/cloud/vision/v1/image_annotator.proto' was not found.
Though I made a rule in my webpack config file to support .proto files.
This is my webpack.config.js :
module.exports = {
target: "node",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.json$/,
exclude: /node_modules/,
use: {
loader: "json-loader"
}
},
{
test: /\.proto$/,
use: {
loader: "pbf-loader"
}
},
{
test: /\.html$/,
use: {
loader: "html-loader"
}
}
]
}
};
At this level, I have no idea how to make those google-cloud .proto files to be integrated in my bundel.js, can someone please guide me ? thanks.
This is the code from grpc.js inside the #google-cloud module that tries to resolve the .proto files paths:
GoogleProtoFilesRoot.prototype.resolvePath = function (originPath, includePath) {
originPath = path.normalize(originPath);
includePath = path.normalize(includePath);
// Fully qualified paths don't need to be resolved.
if (path.isAbsolute(includePath)) {
if (!fs.existsSync(includePath)) {
throw new Error('The include `' + includePath + '` was not found.');
}
return includePath;
}
if (COMMON_PROTO_FILES.indexOf(includePath) > -1) {
return path.join(googleProtoFilesDir, includePath);
}
return GoogleProtoFilesRoot._findIncludePath(originPath, includePath);
};

Using CSS in Webpack

I've inherited a web app that uses webpack. In my app, I have a directory called "pub", which looks like this:
./pub
/styles
app.css
/images
brand.png
I have been trying unsuccessfully all morning to use these via webpack. In my webpack.config.js file, I have the following:
const path = require('path');
const projectRoot = path.resolve(__dirname, '../');
module.exports = {
entry: {
app: './src/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192
}
}
]
}
]
}
};
Then, in my index.js file, I have the following:
import logoImage from './public/images/brand.png';
require("css!./public/css/app.css");
When I run webpack, I receive an error that says:
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.
You need to specify 'css-loader' instead of 'css',
see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
I don't really understand this error. When I look at it, and then I look at my webpack.config.js file, it looks to me like I'm using css-loader. Beyond that though, how do I use a style in my webpage once the require statement is working. I'm just trying to use webpack with a web app and want to import my brand and CSS and I can't figure it out.
You don't need the css! in your require statement
require("css!./public/css/app.css");
You can just use
require("./public/css/app.css");
Because you are testing files with:
{
test: /\.css$/, // <-- here
loader: "style-loader!css-loader"
},
Or without the rule in your webpack config
// No test in rules matched but you tell webpack
// explicitly to use the css loader
require("style-loader!css-loader!./public/css/app.css");
Your hierarchy is pub/styles/app.css but the location you use in your require is public/css/app.css. It looks like you're trying to call your css from the wrong location.
If this doesn't solve your issue, check out this link https://webpack.github.io/docs/stylesheets.html
The first step on that page is to install css-loader and configure it, this might be a good place to start.

Webpack 2 svg files give 404 error

Started working with webpack. In one of my css files I have an url to an svg file, but by using webpack I get 404 error when trying to load this file, tried few loaders first, second and last. Have no idea why its not working, can some one help me or give some info?
EDIT
entry: [
'./src\\main\\resources\\static\\webpack-js\\header.js'
],
output: {
path: path.join(__dirname, 'src/main/resources/static/dist'),
publicPath: '/src/main/resources/static/dist/',
filename: 'bundle.js',
libraryTarget: 'var',
library: 'EntryPoint',
},
module: {
loaders: [
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.(jpe?g|png|gif|svg)$/,
loader: 'url-loader'
},
{
test: /\.js$/,
loader: ['buble-loader'],
exclude: '/node_modules/'
}
],
}
This is my module from webpack.config.js. I am using css file that is required in header.js (entry file). Now in the css file I have lines like this
.vismaicon-menu.vismaicon-info:before {
background-image: url(/static/css/img/vismaicons/top_menu/menu_info.svg);
}
As I mentioned I tried few things to load svg files but I'm getting 404 error. And yes url is correct and files are there, it works without webpack. Everything other than svg works in css files and I get things from it.
Changed my Loaders for svg to this one and giving bigger limit solved my problem.
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=1000000&mimetype=image/svg+xml"
},

React is expected to be globally available

I'm playing with React (#13.3) with babel and webpack.
I have a component that's defined like this:
import BaseComponent from './BaseComponent';
export default class SomeComponent extends BaseComponent {
render() {
return (
<div>
<img src="http://placekitten.com/g/900/600"/>
</div>
);
}
}
But I get the following error:
Uncaught ReferenceError: React is not defined
I understand the error: the JSX bit is compiled into React.createElement(...) but React isn't in the current scope since it's not imported.
My questions is:
What's the clean way to work around this issue? Do I have to somehow expose React globally with webpack?
Solution used:
I followed #salehen-rahman suggestion.
In my webpack.config.js:
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'react-hot!babel?plugins[]=react-require'
}, {
test: /\.css$/,
loader: 'style!css!autoprefixer?browsers=last 2 versions'
}]
},
I also needed to fix my tests, so I added this to the file helper.js:
require('babel-core/register')({
ignore: /node_modules/,
plugins: ['react-require'],
extensions: ['.js']
});
My tests are then launched with the following command:
mocha --require ./test/helper.js 'test/**/*.js'
My questions is : What's the clean way to work around this issue ? Do I have to somehow expose React globally with webpack ?
Add babel-plugin-react-require to your project, and then amend your webpack's Babel config to have settings akin to:
loaders: [
{
test: /.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
stage: 0,
optional: ['runtime'],
plugins: [
'react-require' // <-- THIS IS YOUR AMENDMENT
]
},
}
]
Now, once you've applied the configuration update, you can initialize React components without manually importing React.
React.render(
<div>Yippee! No <code>import React</code>!</div>,
document.body // <-- Only for demonstration! Do not use document.body!
);
Bear in mind though, babel-plugin-react-require transforms your code to automatically include React imports only in the presence of JSX tag in a specific file, for a specific file. For every other file that don't use JSX, but needs React for whatever reason, you will have to manually import React.
If you have react in your node modules directory you can add import React from 'react'; at the top of your file.
You can use Webpack's ProvidePlugin. To use, update the plugins section in your Webpack config to include the following:
plugins: [
new webpack.ProvidePlugin({
'React': 'react'
})
]
This, however, doesn't solve it for the tests..

Categories

Resources