'Cannot find module' when using dynamic import - javascript

I've deleted CRA and configured webpack/babel on my own. Now I have problems with dynamic imports.
This works fine:
import("./" + "CloudIcon" + ".svg")
.then(file => {
console.log(file);
})
This doesn't work:
const name = 'CloudIcon';
import("./" + name + ".svg")
.then(file => {
console.log(file);
})
I've tried to export files with different types. It didn't work.
Have tried to use Webpack Magic Comments, but didn't help either.
I suppose, that something is wrong with my webpack/babel settings, but what?
babel.config.js:
const plugins = [
"#babel/syntax-dynamic-import",
["#babel/plugin-transform-runtime"],
"#babel/transform-async-to-generator",
"#babel/plugin-proposal-class-properties"
];
if (process.env.NODE_ENV === 'development') {
plugins.push('react-refresh/babel');
}
module.exports = {
presets: [[
"#babel/preset-env", {
"debug": false,
"modules": false,
"useBuiltIns": false
}],
['#babel/preset-react', {throwIfNamespace: false}],
'#babel/preset-typescript'
],
plugins,
};
webpack.config.js:
require('dotenv').config();
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ReactRefreshWebpackPlugin = require('#pmmmwh/react-refresh-webpack-plugin');
const webpack = require('webpack');
const reactAppVars = (() => {
const obj = {};
for (let key in process.env) {
if (key.startsWith('REACT_APP_')) obj[key] = process.env[key];
}
return obj;
})();
const target = process.env['NODE_ENV'] === 'production' ? 'browserslist' : 'web';
const plugins = [
new webpack.EnvironmentPlugin({'NODE_ENV': process.env['NODE_ENV'], 'PUBLIC_URL': '', ...reactAppVars}),
new HtmlWebpackPlugin({template: path.resolve(__dirname, '../public/index.html')}),
new MiniCssExtractPlugin({filename: '[name].[contenthash].css'}),
new webpack.ProvidePlugin({process: 'process/browser'}),
new webpack.ProvidePlugin({"React": "react"}),
];
if (process.env['SERVE']) plugins.push(new ReactRefreshWebpackPlugin());
const proxy = {
//Proxy settings
}
module.exports = {
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "../build"),
assetModuleFilename: '[path][name].[ext]'
},
plugins,
devtool: 'source-map',
devServer: {
static: {
directory: path.resolve(__dirname, "../public"),
},
proxy,
port: 9999,
hot: true,
},
module: {
rules: [
{ test: /\.(html)$/, use: ['html-loader'] },
{
test: /\.(s[ac]|c)ss$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.less$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true
}
}
}
]
},
{
test: /\.(png|jpe?g|gif|webp|ico)$/i,
type: process.env['NODE_ENV'] === 'production' ? 'asset' : 'asset/resource'
},
{
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: ['#svgr/webpack', {
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}],
},
{
test: /\.(woff2?|eot|ttf|otf)$/i,
type: process.env['NODE_ENV'] === 'production' ? 'asset' : 'asset/resource'
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
}
}
},
{
test: /\.([cm]?ts|tsx)$/,
use: {
loader: "babel-loader",
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
]
}
}
},
{
test: /\.md$/,
loader: "raw-loader"
},
],
},
resolve: {
'roots': [path.resolve('./src')],
'extensions': ['', '.js', '.jsx', '.ts', '.tsx'],
extensionAlias: {
".js": [".js", ".ts"],
".cjs": [".cjs", ".cts"],
".mjs": [".mjs", ".mts"]
},
fallback: {
'process/browser': require.resolve('process/browser')
}
},
mode: process.env['NODE_ENV'],
target
}

What is basically happen that when you have defined import path, webpack will include that code in already existing chunk.
When you have a dynamic import (which translated to Regex) it will take all files that correspond to this Regex and place them in a different chunk.
It hard to determine from the details if you serve this additional chunks and the browser can reach them. Network and server logs is a good start.
https://webpack.js.org/guides/code-splitting/#prefetchingpreloading-modules

The problem was the extensions array in webpack
'extensions': ['', '.js', '.jsx', '.ts', '.tsx']
I changed it to this
'extensions': ['.js', '.jsx', '.ts', '.tsx', '...']
And now everything works fine.

Related

How to bundle and minimize JS and CSS files with webpack

I have been trying to use webpack for my project. I have successfully got webpack to compile all of my js into one file correctly. But what i need is for it to also get the css. All of my css is in one file so i figured it would be easy but i cant figure it out. I have tried to split it up into 2 phases CSS_CONFIG and JS_CONFIG
const path = require('path');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
var JS_CONFIG = {
entry: path.join(__dirname, 'src/js/main.js'),
resolve: {
alias: {
'/components': path.resolve(__dirname, 'src/components/'),
'/js': path.resolve(__dirname, 'src/js/'),
'/views': path.resolve(__dirname, 'src/views/'),
},
},
optimization: {
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
new TerserPlugin(),
//new CssMinimizerPlugin(),
],
},
}
var CSS_CONFIG = {
entry:path.join(__dirname,"src/index.html"),
module: {
rules: [
{
test: /.s?css$/,
use: [],
},
],
},
optimization: {
minimize:true,
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
// `...`,
//new CssMinimizerPlugin(),
],
},
plugins: [],
}
module.exports = [JS_CONFIG, CSS_CONFIG];
This seems like it should be pretty straightforward with webpack but I must not be grasping somthing. Can anyone help me out?
I believe that your CSS_CONFIG should look more like this:
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
const isDevelopment = process.env.NODE_ENV === 'development'
var config = {
module: {},
};
var cssConfig = Object.assign({}, config, {
devtool: 'source-map',
entry: {
main: path.resolve(__dirname, 'public/css/main.scss'),
fonts: path.resolve(__dirname, 'public/css/fonts.scss'),
app: path.resolve(__dirname, 'public/css/app.scss'),
},
output: {
path: path.resolve(__dirname, 'public/css')
},
performance: {
hints: false
},
plugins: isDevelopment ? [] : [
new RemoveEmptyScriptsPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css'
}),
],
module: {
rules:[
// Extracts the compiled CSS from the SASS files defined in the entry
{
test: /\.scss$/,
use: isDevelopment ?
[
'style-loader',
{
loader: 'css-loader',
options: { sourceMap: true, importLoaders: 1, modules: false },
},
{
loader: 'postcss-loader',
options: { sourceMap: true }
},
{
loader: 'resolve-url-loader',
},
{
loader: 'sass-loader',
options: { sourceMap: true }
},
]
: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) => {
// publicPath is the relative path of the resource to the context
// e.g. for ./css/admin/main.css the publicPath will be ../../
// while for ./css/main.css the publicPath will be ../
return path.relative(path.dirname(resourcePath), context) + "/";
},
},
},
{
loader: 'css-loader',
options: {
importLoaders: 2,
modules: false,
url: false,
},
},
{
loader: 'postcss-loader',
options:
{
postcssOptions:
{
plugins: [
require('postcss-import'),
require('postcss-url')({
url: 'copy',
useHash: true,
hashOptions: { append: true },
assetsPath: path.resolve(__dirname, 'public/assets/')
})
]
}
}
},
{
loader: 'resolve-url-loader',
},
{
loader: 'sass-loader',
options: { sourceMap: true }
},
]
},
/* you may or may not need this
{
test: /\.(woff(2)?|ttf|eot|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
esModule: false,
}
}
]
},
*/
],
}
});
use runs the loaders in order that they are put in the array. So 'style-loader' needs to be executed first. Here is a simple way of achieving the desired result.
const path = require('path');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
const isDevelopment = process.env.NODE_ENV === 'development'
var JS_CONFIG = {
entry: {
main: path.resolve(__dirname, 'src/js/main.js'),
css: path.join(__dirname, 'src/css/main.css'),
},
resolve: {
alias: {
'/components': path.resolve(__dirname, 'src/components/'),
'/js': path.resolve(__dirname, 'src/js/'),
'/views': path.resolve(__dirname, 'src/views/'),
},
},
module: {
rules:[
{
test: /\.css$/,
use:['style-loader','css-loader']
},
],
},
};
module.exports = [JS_CONFIG];

ModuleParseError: Module parse failed: Unexpected character '�'

When i import owl.carousel
I face the below error, What is it exactly, and what can I do for it?
./node_modules/owl.carousel/dist/assets/owl.carousel.css
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleParseError: 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
webpack.config.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const autoprefixer = require("autoprefixer");
const webpack = require("webpack");
module.exports = (env) => {
let clientPath = path.resolve(__dirname, 'src/main/client');
let outputPath = path.resolve(__dirname, (env === 'production') ? 'src/main/resources/static' : 'out')
return {
mode: !env ? 'development' : env,
entry: {
index: ["babel-polyfill", clientPath + '/index.js']
},
output: {
path: outputPath,
filename: '[name].js'
},
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors'
}
}
},
minimizer: (env === 'production') ? [
new UglifyJsPlugin(),
new OptimizeCssAssetsPlugin()
] : []
},
devServer: {
contentBase: outputPath,
publicPath: '/',
host: '0.0.0.0',
port: 8081,
proxy: {
'**': 'http://127.0.0.1:8080'
},
inline: true,
hot: false
},
module: {
rules: [
{
test: /\.js$/,
use: [{
loader: 'babel-loader',
options: {
presets: 'env'
}
}]
},
{
test: /\.(css)$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
loader: 'css-loader'
},
{
loader: "postcss-loader",
options: {
plugins: () => {
return [
autoprefixer({
overrideBrowserslist: "cover 99.5%"
})
];
}
}
},
]
},
{
test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]',
outputPath: 'urls/'
}
}
},
{
test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}
}
]
},
plugins: [
new MiniCssExtractPlugin({
path: outputPath,
filename: '[name].css'
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
]
}
}
Why This Error appear?
ADD
It's happen every file ( also semantic ui )
the strange character you see has to do with the icon's image they have, I'm assuming you have url-loader and file-loader installed but I see that you are using the outputPath! which I think it's the source of the problem?
Here is a simple configuration that worked for me:
{
test: /\.(png|jpg|gif|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: '[name].[hash:7].[ext]'
},
},
],
}
You can copy it or just get rid of the outputPath and see if this solve your issue :)

Code splitting not happening via React lazy import ,and Webpack

//webpack dev
const common = require("./webpack.common");
const merge = require("webpack-merge");
const globImporter = require('node-sass-glob-importer');
module.exports = merge(common, {
mode: "development",
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')({
'overrideBrowserslist': ['> 1%', 'last 2 versions']
})],
}
},
{
loader: 'sass-loader', options: {
sassOptions: {
importer: globImporter()
}
}
}]
},
]
},
devServer: {
// contentBase: path.join(__dirname, 'dist'),
historyApiFallback: true,
port: 8081
}
});
//webpack prod
const common = require("./webpack.common");
const path = require("path");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const merge = require("webpack-merge");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = merge(common, {
mode: "production",
output: {
filename: "main.[contenthash].js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
{ loader: MiniCssExtractPlugin.loader },
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')({
'overrideBrowserslist': ['> 1%', 'last 2 versions']
})],
}
},
{
loader: 'sass-loader', options: {
sassOptions: {
importer: globImporter()
}
}
}]
}
]
},
plugins: [new MiniCssExtractPlugin({
filename: "./src/css/[name].[contentHash].css"
},
), new CleanWebpackPlugin()]
})
// webpack common
const HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports={
entry:"./src/index.tsx",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx",".js", ".jsx"]
},
module:{
rules:[
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
{
test:/\html$/,
use:["html-loader"]
},
{
test:/\.(svg|png|jpe?g|gif)$/i,
use:{
loader:"file-loader",
options:{
name:"[name].[hash].[ext]",
outputPath:"images"
}
}
}
]
},
// externals: {
// "react": "React",
// "react-dom": "ReactDOM"
// },
plugins:[new HTMLWebpackPlugin({
template:"./src/index.html"
})]
}
Code splitting not happening via React lazy import ,and Webpack
I want to do code splitting with React Suspense and Lazy imports , I don't know what is missing because separate chunk is not getting created for my dynamically import component
Please anyone help I am using webpack 4 and React version 16.9
Getting below message warning console
WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB).
This can impact web performance.
Entrypoints:
main (533 KiB)
./src/css/main.000e3971ce67d214e0d7.css
main.5877aa0d0c3e45fb034f.js
WARNING in webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/
In tsconfig.json set "module": "esnext"

Webpack Build Speed performance

The Webpack Bulid runs pretty slow, project background is a community portal developed in Vue.js...
Can anybody tell if there is any potential for improvement and if so, what?
I wonder if the time for the build process of 37401ms can still be changed by changing the codebase?
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const glob = require('glob');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const autoprefixer = require('autoprefixer');
const statsSettings = {
all: false,
modules: true,
maxModules: 0,
errors: true,
warnings: false,
moduleTrace: true,
errorDetails: true,
timings: true,
performance: true,
builtAt: true,
};
const {
rootDir,
srcDir,
assetsDir,
stylesDir,
buildDir,
sitepackageDir,
publicPath,
} = require('./config');
const chunks = glob.sync(path.join(rootDir, srcDir, 'pages/**/index.js'))
.reduce((obj, file) => {
const name = path.basename(path.dirname(file));
return {
...obj,
[name]: file,
};
}, {});
module.exports = env => {
return {
mode: env.production ? 'production' : 'development',
context: path.join(rootDir, srcDir),
entry: chunks,
output: {
path: path.join(rootDir, buildDir),
filename: '[name].js',
publicPath: env.production ? publicPath : '',
},
devtool: env.production ? false : 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(rootDir, buildDir),
inline: true,
proxy: {
'/api/v0': 'http://localhost:4000',
},
},
watchOptions: {
ignored: env.watch ? 'node_modules' : '',
aggregateTimeout: 300,
},
stats: env.watch ? statsSettings : 'normal',
module: {
rules: [
{
test: /\.vue$/,
include: [
path.join(rootDir, srcDir),
require.resolve('bootstrap-vue'),
],
loader: 'vue-loader',
},
{
test: /\.js$/,
include: [
path.join(rootDir, srcDir),
require.resolve('bootstrap-vue'),
],
loader: 'babel-loader',
},
{
test: /\.(css|scss)$/,
use: [
env.production ? MiniCssExtractPlugin.loader : 'vue-style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: [
autoprefixer({
browsers: ['>1%', 'last 2 versions', 'not ie < 11'],
}),
],
},
},
{
loader: 'sass-loader',
options: {
includePaths: [
path.join(rootDir, srcDir, stylesDir),
],
},
},
],
},
{
test: /\.(jpg|jpeg|png|gif|webp|svg|eot|otf|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$/,
loader: 'file-loader',
options: {
name: `${assetsDir}/_processed_/[name].[hash:4].[ext]`,
},
},
],
},
optimization: {
runtimeChunk: {
name: '_runtime',
},
splitChunks: {
cacheGroups: {
// we need to figure out if it's worth having a common chunk
// or if each entry chunk should be somewhat self-contained
common: {
chunks: 'initial',
name: '_common',
minChunks: 2,
minSize: 0,
},
vendor: {
test: /node_modules/,
chunks: 'initial',
name: '_vendor',
enforce: true,
},
},
},
},
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
'#app': path.join(rootDir, srcDir),
// although we're using single file components that can be pre-compiled,
// we want to dynamically mounting them in the DOM html.
// this is way we need to alias 'vue' to use the runtime + compiler build here.
// see: https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
vue$: 'vue/dist/vue.esm.js',
},
},
plugins: [
new webpack.DefinePlugin({
PAGES: JSON.stringify(Object.keys(chunks)),
}),
new VueLoaderPlugin(),
...plugHtmlTemplates(),
...plugExtractCss(env),
...plugCopyAssets(),
],
};
};
function plugHtmlTemplates () {
return glob.sync(path.join(rootDir, srcDir, 'pages/**/template.html'))
.map(template => {
const name = path.basename(path.dirname(template));
return {
template,
filename: `${name}.html`,
chunks: ['_runtime', '_vendor', '_styles', '_common', name],
};
})
.map(htmlConfig => new HtmlWebpackPlugin(htmlConfig));
}
function plugExtractCss (env) {
if (!env.production) return [];
return [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[name].css',
}),
];
}
function plugCopyAssets () {
const assetsSrcPath = path.join(rootDir, srcDir, assetsDir);
if (!fs.existsSync(assetsSrcPath)) return [];
return [
new CopyWebpackPlugin([
{ from: assetsSrcPath, to: path.join(rootDir, buildDir, path.basename(assetsDir)) },
// this is required for the icons to be selectable in the backend
{ from: path.join(assetsSrcPath, 'icons/'), to: path.join(rootDir, sitepackageDir, 'Resources/Public/Icons/') },
// this is required for avatars to be available; we must not check them in in fileadmin since they would
// prevent having the dir linked by Deployer during a deployment
{ from: path.join(rootDir, '../packages/users/Resources/Private/Images/Avatars/'), to: path.join(rootDir, buildDir, 'static/avatars/') },
]),
];
}
The question is whether you can improve the performance by using different plugins or summarizing steps...
I have a similar configuration. My configuration built ~33 seconds. I added a cache-loader package and decrease build time to ~17 seconds.
npm install --save-dev cache-loader
config:
rules: [
//rules here
{
test: /\.vue$/,
use: [
{
loader: 'cache-loader',
options: {}
},
{
loader: 'vue-loader',
options: vueLoaderConfig
}
],
},
{
test: /\.js$/,
use: [
{
loader: 'cache-loader',
options: {}
},
{
loader: 'babel-loader'
}
],
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
}
]

404 not found ( webpack image )

How can I import an image using this web pack config?
I get the following error in the console after I build the app using yarn build. How can I import the image to the dashboard file from the assets/public folder? (please see image). Thanks in advance.
this the webpack config file.
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const extractCSS = new ExtractTextPlugin('[name].fonts.css');
const extractSCSS = new ExtractTextPlugin('[name].styles.css');
const BUILD_DIR = path.resolve(__dirname, 'build');
const SRC_DIR = path.resolve(__dirname, 'src');
console.log('BUILD_DIR', BUILD_DIR);
console.log('SRC_DIR', SRC_DIR);
module.exports = (env = {}) => {
return {
entry: {
index: [SRC_DIR + '/index.js']
},
output: {
path: BUILD_DIR,
filename: '[name].bundle.js',
},
// watch: true,
devtool: env.prod ? 'source-map' : 'cheap-module-eval-source-map',
devServer: {
contentBase: BUILD_DIR,
// port: 9001,
compress: true,
hot: true,
open: true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: ['react', 'env']
}
}
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(scss)$/,
use: ['css-hot-loader'].concat(extractSCSS.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {alias: {'../img': '../public/img'}}
},
{
loader: 'sass-loader'
}
]
}))
},
{
test: /\.css$/,
use: extractCSS.extract({
fallback: 'style-loader',
use: 'css-loader'
})
},
{
test: /\.(png|jpg|jpeg|gif|ico)$/,
use: [
{
// loader: 'url-loader'
loader: 'file-loader',
options: {
name: './img/[name].[hash].[ext]'
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader',
options: {
name: './fonts/[name].[hash].[ext]'
}
}]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.UglifyJsPlugin({sourceMap: true}),
new webpack.NamedModulesPlugin(),
extractCSS,
extractSCSS,
new HtmlWebpackPlugin(
{
inject: true,
template: './public/index.html'
}
),
new CopyWebpackPlugin([
{from: './public/img', to: 'img'}
],
{copyUnmodified: false}
)
]
}
};
Please see images below.
What Am I missing here?
Thanks in advance.
first of all , you should import your image like :
import MyImage from '../relative/path/to/your/image'
then use it like:
function App() {
return (
<div className="App">
<img src={MyImage} alt='any kind of description'>
</div>
);
}

Categories

Resources