images not loading in html using webpack - javascript

I'm having any issue loading images from a different folder than where my index.html file is located. Below is the message I am getting from the console.
GET http://localhost:3000/company-logo.jpg 404 (Not Found)
Here is my file directory
webpack.config.js
const currentTask = process.env.npm_lifecycle_event
const path = require('path')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const fse = require('fs-extra')
const postCSSPlugins = [
require('postcss-import'),
require('postcss-simple-vars'),
require('postcss-nested'),
require('autoprefixer')
]
class RunAfterComile {
apply(compiler) {
compiler.hooks.done.tap('Copy images', function() {
fse.copySync('./public/images', './dist/public/images')
})
}
}
let cssConfig = {
test: /\.css$/i,
use: ['css-loader?url=false', {loader: 'postcss-loader', options: {plugins: postCSSPlugins}}]
}
let pages = fse.readdirSync('./views').filter(function(file) {
return file.endsWith('.html')
}).map(function(page) {
return new HtmlWebpackPlugin({
filename: page,
template: `./views/${page}`
})
})
let config = {
entry: './public/scripts/App.js',
plugins: pages,
module: {
rules: [
cssConfig
]
}
}
if (currentTask == 'dev') {
cssConfig.use.unshift('style-loader')
config.output = {
filename: 'bundled.js',
path: path.resolve(__dirname, 'public')
}
config.devServer = {
before: function(app, server) {
server._watch('./views/**/*.html')
},
contentBase: path.join(__dirname, './views'),
hot: true,
port: 3000
}
config.mode = 'development'
}
if (currentTask == 'build') {
config.module.rules.push({
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
})
cssConfig.use.unshift(MiniCssExtractPlugin.loader)
postCSSPlugins.push(require('cssnano'))
config.output = {
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'dist')
}
config.mode = 'production'
config.optimization = {
splitChunks: {chunks: 'all'}
}
config.plugins.push(
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({filename: 'styles.[chunkhash].css'}),
new RunAfterComile()
)
}
module.exports = config
The css works perfectly fine. I seem to only be having problems with images.
I tried the following file paths but they didn't work. I think I am missing something.
index.html
<img src="./company-logo.jpg" alt="dfgadfg">
<img src="../public/images/company-logo.jpg" alt="dfgadfg">
<img src="./images/company-logo.jpg" alt="dfgadfg">
any help would be appreciated. Thank you very much.

Try use
module: {
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
],
},
],
},

You might require file-loder to get the images correctly served
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
outputPath: 'images' // Chage this like 'public/images' or any other relative path to the root
}
},
...
]
Try to inspect and check how the images are loading in Source tab of Developer Tools, change the outputPath accordingly.
Update
If images are still not loading to Source tab of browser, try importing it in your App.js (Entry point file)
....
import "../public/images/company-logo.jpg";
...

Related

Why aren't my stylesheets being included in the Webpack build?

Webpack collected files (.css, .js) into a library and use it in another React project. The styles specified in the component do not pass, although the .css file is present and the styles are there.
UiButton.jsx file
import styles from './UiButton.module.css';
const UiButton = () => {
return (
<>
<button className={styles.button}>Text</button>
</>
);
}
export default UiButton;
index.js file
import UiButton from './UiButton/UiButton';
import './index.css';
export { UiButton };
Webpack.config.js file
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: { main: './src/index.js' },
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
libraryTarget: "umd",
library: "uilibrarytest"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [ 'style-loader', MiniCssExtractPlugin.loader, 'css-loader' ]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'index.css',
}),
// new HtmlWebpackPlugin({
// template: './public/index.html',
// }),
new webpack.ProvidePlugin({
"React": "react",
}),
],
resolve: {
extensions: ['.js', '.jsx'],
},
}
This is what webpack builds:
.button {
background: red;
}
html {
margin: 0;
padding: 0;
}
How to make it so that when using a component from a given library, the styles are also pulled to it ???
Loaders in Webpack are evaluated from right to left. In your configuration the evaluation order is 'css-loader', MiniCssExtractPlugin.loader, and finally 'style-loader'. But 'style-loader' only injects styles into the DOM. You need MiniCssExtractPlugin.loader to be the first element in the "use" array. See below...
{
test: /\.css$/,
use: [ MiniCssExtractPlugin.loader, 'css-loader' ]
}
Furthermore you can tell webpack to use MiniCssExtractPlugin.loader during production and at other times use 'style-loader'.
const isProduction = process.env.NODE_ENV == 'production';
const stylesHandler = isProduction ? MiniCssExtractPlugin.loader : 'style-loader';
...other config
{
test: /\.css$/,
use: [ stylesHandler, 'css-loader' ]
}
And in your package.json scripts,
"build": "webpack --mode=production --node-env=production"

Doing a dynamic import in a loop, walking through the array, but I only get the first value

I am trying to do a dynamic import so that my classes are pulled by information from json. In json, I only have classes specified that I need to get inside the script. I make paths from strings to json then put them in an array.I make an import and put the values ​​into an array. But as a result, I only get the value of the first import, the rest is undefined. Tell me how to correctly perform dynamic imports inside a loop, or is there a fundamentally different approach altogether?
My index.js:
var popupsConfig = myConfig.popups
var popups = []
async function getPopups(popupsConfig) {
for (let i = 0; i < popupsConfig.length; i++) {
let obj = await
import (`../src/assets/popups/${myConfig.popups[i].popupType}`)
popups.push(obj.default)
}
}
getPopups(popupsConfig)
My webpack.config:
const webpack = require("webpack")
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
context: path.resolve(__dirname, '../src'),
mode: 'development',
devtool: "eval-source-map",
entry: {
entry: ['babel-polyfill', '../dev/index.js'],
},
devServer: {
port: 8080
},
experiments: {
topLevelAwait: true
},
resolve: {
alias: {
'#dev': path.resolve(__dirname, '../src/')
}
},
plugins: [
new HtmlWebpackPlugin({
template: '../dev/index.html'
}),
new CleanWebpackPlugin(),
new webpack.DefinePlugin({
CANVAS_RENDERER: JSON.stringify(true),
WEBGL_RENDERER: JSON.stringify(true)
})
],
module: {
rules: [{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpeg|svg|gif)$/,
use: ['file-loader']
}, {
test: [/\.vert$/, /\.frag$/],
use: "raw-loader"
},
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
}
My .babelrc:
{
"plugins": ["dynamic-import-webpack", "#babel/plugin-syntax-dynamic-import"]
}
enter image description here

Uncaught ReferenceError: __webpack_require__ is not defined Deploying to server

I am getting this error when logging into our dev site. This is a part of our migration from .NET framework 4.5.2 to 4.7.2. Though I do not think that has much to do with it. If we publish straight from VS, the page loads fine. If it uses our pipeline, or we did not clear our dirs beforehand, we get this error (in the console browser).
ie-polyfill_aurelia-bootstrapper:1 Uncaught ReferenceError:
webpack_require is not defined
at eval (ie-polyfill_aurelia-bootstrapper:1)
at Object.0 (xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1)
at t (xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1)
at xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1
at xxxAppScripts?v=sRzkW2d1FsbC87Brht0ZS8CXZDQaGBaky9ddApOJOaY1:1
The process of our build should be exactly the same as building with NPM locally, and there are no errors given in the build process. Build is defined for both in the webpack.config.js as follows
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { ProvidePlugin, SourceMapDevToolPlugin } = require('webpack')
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');
const CleanWebpackPlugin = require('clean-webpack-plugin');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || []
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig)
// primary config:
const title = 'XXXXXX';
const outDir = path.resolve(__dirname, 'Scripts', 'pub');
const srcDir = path.resolve(__dirname, 'App');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
var isDevBuild = true;
var dev;
if (process.env.NODE_ENV) {
dev = process.env.NODE_ENV.trim();
if (dev === "production") {
isDevBuild = true;
}
}
const cssRules = [
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })] }
},
'sass-loader'
];
module.exports = ({ production, server, extractCss, coverage } = {}) => ({
resolve: {
extensions: ['.ts', '.js'],
modules: [srcDir, 'node_modules'],
plugins: [
new TsConfigPathsPlugin(),
],
alias: {
// Enforce single aurelia-binding, to avoid v1/v2 duplication due to
// out-of-date dependencies on 3rd party aurelia plugins
'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding'),
'aurelia-bootstrapper': path.resolve(__dirname, 'node_modules/aurelia-bootstrapper')
}
},
entry: {
app: ['./ie-polyfill', 'aurelia-bootstrapper'],
vendor: ['jquery'],
},
output: {
path: outDir,
publicPath: baseUrl,
filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
chunkFilename: production ? '[chunkhash].chunk.js' : '[hash].chunk.js',
},
devServer: {
contentBase: baseUrl,
// serve index.html for all 404 (required for push-state)
historyApiFallback: '/',
},
module: {
rules: [
{
test: /\.css$/i,
issuer: [{ not: [{ test: /\.html$/i }] }],
use: extractCss ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssRules,
}) : ['style-loader', ...cssRules],
},
{
test: /\.css$/i,
issuer: [{ test: /\.html$/i }],
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
use: cssRules,
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader']
})
},
{ test: /\.html$/i, loader: 'html-loader' },
{ test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
{
test: require.resolve("jquery"),
use: [
{
loader: "expose-loader",
options: "$"
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
// required polyfills for non-evergreen browsers
new ProvidePlugin({
Map: 'core-js/es6/map',
WeakMap: 'core-js/es6/weak-map',
Promise: 'core-js/es6/promise',
regeneratorRuntime: 'regenerator-runtime' // to support await/async syntax
}),
new AureliaPlugin({
aureliaApp: 'main'
}),
new ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
}),
new CheckerPlugin(),
new ExtractTextPlugin({
filename: production ? '[contenthash].css' : 'style-[id].css',
allChunks: true,
}),
].concat(isDevBuild ? [
new SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(outDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
new UglifyJsPlugin()
]),
})
There do seem to be a few times a similar question has been asked, but there has not been a solution that worked. Thanks for any help provided.

Unexpected token You may need an appropriate loader to handle this file type.importing strapi sdk

Hi I am trying to import javascript strapi sdk (link) in my new project which is configured using web pack
Here is my code yet
index.ts file
import * as $ from 'jquery';
import Strapi from 'strapi-sdk-javascript'
const strapi = new Strapi('http://localhost:1337')
here is my webpack.config.file
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.js$/,
use:
{loader: 'babel-loader',
options: {
presets: ['env']
}
},
// include: [path.resolve(__dirname, "./src/app")],
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
alias: {
$: "jquery/src/jquery",
}
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
template: 'src/assets/template.html'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
and this is giving my this error
what am i doing wrong here . please
help thanks in advance
You can try something like this
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: [path.resolve(__dirname,"./src/app")path.resolve('node_modules/strapi-sdk-javascript')],
loader: require.resolve('babel-loader'),
},

how to install reactjs npm package correctly

Hi I want to install this reactjs package called react-dropdown-input
https://github.com/RacingTadpole/react-dropdown-input/
I ran this command
$npm install react-dropdown-input --save
in my local folder in git bash. After that I checked my package.json, it says "react-dropdown-input": "^0.1.11" which means i have installed it correctly.
Then i tried to use it in my js file
import React from 'react'
import PropTypes from 'prop-types';
var DocumentTitle = require('react-document-title');
//var DropdownInput = require('react-dropdown-input');
When i added the fifth line, my page just could not load anymore (a blank page)
I dont know how to fix this.
Here's my webpack.config.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const path = require('path');
const webpack = require('webpack');
const BaseFolder = 'static/'; //relative to html path
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractLess = new ExtractTextPlugin({
filename: '[name].[contenthash].css',
disable: process.env.NODE_ENV === 'development'
});
var loaders = ['babel-loader'];
var port = process.env.PORT || 3000;
var vendor = ['react', 'react-dom', 'react-router', 'whatwg-fetch', 'es6-promise'];
var outputDir = 'dist';
var entry = {
filename: path.resolve(__dirname, 'src/app.js'),
}
var plugins = [
new webpack.optimize.CommonsChunkPlugin({
name:'vendor',
minChunks: Infinity,
filename: BaseFolder + 'js/[name].js',
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, '/src/index.html'),
filename: 'index.html',
inject: 'body'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'BaseFolder': JSON.stringify(BaseFolder)
}),
//new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
extractLess,
new webpack.ProvidePlugin({
Promise: 'es6-promise',
fetch: 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch',
React: 'react',
jsSHA: 'jssha',
wx: 'weixin-js-sdk'
}),
new CopyWebpackPlugin([
{
from: 'src/images',
to: BaseFolder + 'images'
}
])
];
if (process.env.NODE_ENV === 'development') {
//devtool ='eval-source-map';
loaders = ['react-hot-loader'].concat(loaders);
plugins = plugins.concat([
new webpack.HotModuleReplacementPlugin()
]);
entry = Object.keys(entry).reduce(function (result, key) {
result[key] = [
'webpack-dev-server/client?http://0.0.0.0:' + port,
'webpack/hot/only-dev-server',
entry[key]
];
return result;
}, {});
}
entry.vendor = vendor;
module.exports = env => {
return {
entry: entry,
output: {
filename: BaseFolder+'js/bundle.js',
chunkFilename: BaseFolder+'js/[id].chunk.js',
path: path.resolve(__dirname, outputDir),
publicPath: '/'
},
externals: [
],
module: {
loaders: [
{
test: /.jsx?$/,
loader: loaders,
exclude: /node_modules/,
include: __dirname
},
{ test: /\.js$/, exclude: /node_modules/, loaders: loaders, include: __dirname},
{ test: /\.scss$/, exclude: /node_modules/, loader: 'style-loader!css-loader?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap&includePaths[]=node_modules/compass-mixins/lib'},
{ test: /\.css$/, loader: 'style-loader!css-loader', exclude: /\.useable\.css$/},
{
test: /\.useable\.css$/,
use: [
{
loader: 'style-loader/useable'
},
{ loader: 'css-loader' },
],
},
{ test: /\.(png|jpg|jpeg|gif)$/, loader: 'url-loader?limit=100000&name='+BaseFolder+'images/[name].[ext]' },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name='+BaseFolder+'fonts/[name].[ext]' },
{ test: /\.(woff|woff2)$/, loader:'url-loader?prefix=font/&limit=5000&name='+BaseFolder+'fonts/[name].[ext]' },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/octet-stream&name='+BaseFolder+'fonts/[name].[ext]' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml&name='+BaseFolder+'images/[name].[ext]' },
]
},
plugins: plugins
}
};
Yes this must be included in your node_modules, but the point is that you have include that in your compiled js file or not, i.e.
you must have used webpack or gulp to compile all your dependencies of js to give one file and you must have forget to include that dependency file in webpack file or gulpfile, Please check or provide sample of your webpack or gulpfile.
I think that DropdownInput is named export from react-dropdown-input since in index.js file in the repository its exported as
module.exports = DropdownInput;
So need to import it like
import {DropdownInput} from 'react-dropdown-input'

Categories