Correctly bundled image could not be loaded - javascript

I have a very simple React component, that is supposed to display an image.
I am also using Webpack for bundling.
It's probably worth noting that I am using ReactJS.NET.
Although the webpack bundle builds properly, and the .jpg generated by webpack is viewable (using Windows Photo Viewer, for example), the image does not display in my View.
When I take a peek into inspector, the html structure is built properly, but I am getting:
"Could not load the image" - when I hover over the image path.
I made sure that the image path is correct.
Below is my react component:
var React = require('react');
var BackgroundImg = require('./Images/img_fjords.jpg');
class Login extends React.Component {
render() {
return (
<img src={BackgroundImg} />
);
}
componentDidMount() {
console.log("Mounted");
}
}
module.exports = Login;
Webpack config:
var path = require('path');
var WebpackNotifierPlugin = require('webpack-notifier');
module.exports = {
context: path.join(__dirname, 'App'),
entry: {
server: './server',
client: './client'
},
output: {
path: path.join(__dirname, 'Built/'),
publicPath: path.join(__dirname, 'Built/'),
filename: '[name].bundle.js'
},
plugins: [
new WebpackNotifierPlugin()
],
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" },
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff"
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' },
{ test: /\.jsx$/, loader: 'jsx-loader?harmony' }
]
},
resolve: {
// Allow require('./blah') to require blah.jsx
extensions: ['.js', '.jsx']
},
externals: {
// Use external version of React (from CDN for client-side, or
// bundled with ReactJS.NET for server-side)
react: 'React'
}
};

The problem was solved thanks to help from #Luggage.
The webpack.config was wrong, it should have been:
output: {
path: path.join(__dirname, 'Built/'),
publicPath: 'Built/',
filename: '[name].bundle.js'
},

Well, I can't see your webpack config, but I'm assuming your using all the correct loaders (file-loader, extract-loader, html-loader, url-loader)? The way I handle it is using the webpack-copy-plugin to copy over my images folder so relative paths still work.

Related

How to merge bundles with webpack

I'm developing a few React components with the intention of adding them to our Webflow site. For that, I've added an entry for each component in my webpack.config.js file. Now, it looks like this:
const path = require("path");
module.exports = {
entry: {
component_a: "./src/components/a.js",
component_b: "./src/components/b.js",
component_c: "./src/components/c.js",
},
mode: "production",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(pdf|jpg|png|gif|svg|ico)$/,
use: [
{
loader: "url-loader"
}
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: "file-loader"
}
]
},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
output: {
path: __dirname + "/dist",
publicPath: "/",
filename: "bundle_[name].js"
},
devServer: {
static: {
directory: path.join(__dirname, "dist")
}
}
};
This generates me a few bundle_<component_name>.js files, which works great!
But then, there was a need of adding react-map-gl for some of those components, and that's where the issue began: I was having an issue with react-map-gl when doing npm run build and this solved it. But at the same time, a new bundle_mapbox-gl-csp-worker.worker.js is generated for me and all of my built components that depend on it have something like this:
{return new Worker(i.p+"bundle_mapbox-gl-csp-worker.worker.js")}
Although it works fine for our container deployment (because it will always look for bundle_mapbox-gl-csp-worker.worker.js on the same origin and this file will exist), whenever I try to add <script src="https.../bundle_my_component.js"> to Webflow, it will look for https://my-webflow.domain/bundle_mapbox-gl-csp-worker.worker.js, which doesn't exist.
I've tried to replace i.p+"bundle_mapbox-gl-csp-worker.worker.js" to somewhere this script is known to exist, but then I get Script at 'https://.../bundle_mapbox-gl-csp-worker.worker.js' cannot be accessed from origin 'https://some.other.origin'.
I wonder if there's a way of merging my component and the bundle_mapbox-gl-csp-worker.worker.js somehow, either through webpack or something. Or any other workaround for this.

React/Webpack - Image not loading due to wrong path

having a little trouble with webpack loading my images. I'm getting this error:
GET http://localhost:1234/projects/images/KanbanCard0-70090cba.png 404 (Not Found)
I know that's not the path, if I take out projects so it will be localhost:1234/images/Kan... then the image will load.
This is my tree folder:
This is my component:
import React, { Component} from "react";
import kanban2 from '../../images/KanbanCard0.png';
class Kanban extends Component {
render(){
console.log(this.props)
return(
<div className="introWrapper">
<h2>kanban page</h2>
<a onClick={this.props.history.goBack}>Back</a>
<img src={kanban2} />
</div>
);
}
}
export default Kanban;
Webpack.config file
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin')
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
// publicPath: '/projects/'
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.scss?/,
loader: 'style-loader!css-loader!sass-loader'
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[name]-[hash:8].[ext]'
}
}
]
}
]
},
plugins: [
new CopyWebpackPlugin([
{ from: './index.html', to: './index.html' }
])
],
devServer: {
publicPath: '/',
contentBase: __dirname + '/dist',
port: 1234,
historyApiFallback: {
index: 'index.html'
}
}
};
module.exports = config;
I've added a publicPath with images/ and remove in file-loader name -> images/. This will work but it adds the image outside the image folder under dist folder, so it's next to my bundle.js. I would like to keep my images under dist/images just to be organized but I get that GET error because of the projects/images, and it should be images/kanban.....
I'm new to webpack/react, can anyone help with the issue? your help will be appreciated!
Note:
So the word projects is in the error url -> GET http://localhost:1234/projects/images/KanbanCard0-70090cba.png 404 (Not Found). It because I'm under this page, where I want to load my image: http://localhost:1234/projects/kanban_board. I do know that the image is under this path -> http://localhost:1234/images/KanbanCard0-70090cba.png. Just webpack seems not to find, so it looks like it's a config/path issue.
Found my issue, just needed to add a slash in the name:
options: {
name: '/images/[name]-[hash:8].[ext]'
}

How to customize webpack build script for React App

I am moving a web app to react, therefore and moving from Grunt as a buildtool over to webpack. Right now, the below code is the webpack.config file. This is set up as recommended for developing and then has a build script (npm run and npm build)
However, the build script now only concatenates the components/react js files and puts them at the root of the dist folder. No other files are copied over. I don't understand the point of the build script if that's all it does. But I need to be able to add that in, however, no resource with reacts build scripts shows how you would go about that
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./app/src/components/app.js",
output: {
path: path.join(__dirname, "/dist"),
filename: "index_bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./app/index.html"
})
]
};
you do not need a '/'
output: {
path: path.join(__dirname, "dist"),
filename: "index_bundle.js"
},

Webpack output is empty object

I want to build a react component library as a node module to then import it into different projects. But if I try to import a component it just returns an empty object.
button.jsx:
import React, {Component} from 'react'
export class Button extends Component {
render() {
return <button className='btn'>Hello Button comp</button>
}
}
export default Button
index.js
var Button = require('./button/button').default;
module.exports = {
Button: Button
}
webpack.config.js
const Path = require('path');
module.exports = {
resolve: {
extensions: ['.js', '.jsx']
},
entry: {
app: './src/components/index.js'
},
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: [
'es2015',
'react'
]
},
exclude: /node_modules/,
include: [
Path.resolve(__dirname, 'src')
]
},
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: [
'es2015',
'react'
]
},
exclude: /node_modules/,
include: [
Path.resolve(__dirname, 'src')
]
}
]
}
}
Main property in package.json is bundle.js
I figured out that when I import Button in a project it is just an empty object. It seems to me as if webpack doesn't bundle the index file properly. Any ideas what could be wrong here?
A webpack bundle does not expose your exports by default, as it assumes that you're building an app and not a library (which is the far more common use of webpack). You can create a library by configuring output.library and output.libraryTarget.
output: {
path: __dirname,
filename: 'bundle.js',
library: 'yourLibName',
libraryTarget: 'commonjs2'
},
output.libraryTarget is the format of the module, which would also allow you to expose the library as a global variable. commonjs2 is the module format that Node uses. See What is commonjs2? for the difference between commonjs and commonjs2.
Since you're using React, you'll expect that the consumer of the library will have React present as a dependency and therefore you don't want to include it in your bundle. To do that you can define it as an External. This is shown in Authoring Libraries, which walks you through a small example.

Typescript: How to have some imports in the global scope?

Context:
I work on a project where the senior programmer decided to reduce the boilerplate code in newly created typescript files. Two examples of this boilerplate code would be importing the React library or the function that fetches and processes our localized strings.
Question:
Is it possible to have imports always available in files placed in certain folders without having to write the import tags every time?
What I've tried:
I've searched and read on the subject and found those links that talk about defining variables to use in the global space:
global.d.ts, global-modifying-module.d.ts, A typescript issue that seems to get it working
However, I was still unable to get it to work. Here is what I've tried:
At the root of the folder where I want React to be always available, I created a global.d.ts file which contains:
import * as R from "react";
declare global{
const React: typeof R;
}
With this file, the resource "React" is supposed to always be available to other files in subsequent folders. My IDE (Webstorm) recognizes that the import is there and allows me to manipulate the variable React without complaining. However, when I try to run the app, I get this error:
ReferenceError: React is not defined
I don't understand what is wrong with the code! Here is an example of the file I'm trying to render:
export default class World extends React.Component<{}, any> {
public render() {
return (<div>Hello world</div>);
}
}
From this stackoverflow question, I was under the impression that the problem could be webpack related. For the sake of completeness, here is the webpack config file we're currently using:
const webpack = require('webpack');
const path = require('path');
const BUILD_DIR = path.resolve(__dirname, './../bundles');
const WEBPACK_ENTRYFILE = path.resolve(__dirname, './../srcReact/ReactWrapper.tsx');
// `CheckerPlugin` is optional. Use it if you want async error reporting.
// We need this plugin to detect a `--watch` mode. It may be removed later
// after https://github.com/webpack/webpack/issues/3460 will be resolved.
const { CheckerPlugin } = require('awesome-typescript-loader');
const config = {
entry: [WEBPACK_ENTRYFILE],
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.less']
},
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
plugins: [
new CheckerPlugin()
],
devtool: 'source-map', // Source maps support ('inline-source-map' also works)
module: {
loaders: [
{
loader: 'url-loader',
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.(ts|tsx)$/,
/\.css$/,
/\.less$/,
/\.ttf/,
/\.woff/,
/\.woff2/,
/\.json$/,
/\.svg$/
],
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
{
loader: 'url-loader',
test: /\.(ttf|woff|woff2)$/
},
{
loader: "style-loader!css-loader!less-loader",
test: /\.less$/
},
{
loader: "style-loader!css-loader",
test: /\.css$/
},
{
loader: "svg-loader",
test: /\.svg$/
},
{
loader: "json-loader",
test: /\.json$/
},
{
loader: "awesome-typescript-loader",
test: /\.(ts|tsx)$/
}
]
}
};
module.exports = config;
I am certain I am missing something. Can anyone help me?
Surely already open followed a tutorial like this
To do this creates a vendor file where you import these types of "global".
./src/vendors.ts;
import "react";
Add this file a to first place at entry parameter:
entry: { 'vendors': './src/vendors.ts', 'main': './src/main.ts' }
And add CommonChunkPlugins:
plugins: [ new CommonsChunkPlugin({
name: 'vendors'
}),
Like this in AngularClass with polyfills.

Categories