how to import image from JS file - javascript

I am practicing on the webpack project. I got the error while I am importing the img file. I am new for webpack. I have installed the "image-webpack-loader" but still got the error.
Here is the webpack.config.js code
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const config = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
},
{
loader: ExtractTextPlugin.extract({
loader: 'css-loader'
}),
test: /\.css$/
},
{
test: /\.(jpe?g | png | gif |svg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 40000
}
},
'image-webpack-loader'
]
}
]
},
plugins: [
new ExtractTextPlugin('style.css')
]
};
module.exports = config;
And Here is the image_viewer.js file
import '../assets/big.jpg';
import '../assets/small.jpg';
import '../styles/image_viewer.css';
const image = document.createElement('img');
image.src = 'http://lorempixel.com/400/400';
document.body.appendChild(image);
I can't find the solution for this issue. You can see the issue. The style.css and build.js is properly bundled but when I work for image it does not work got some error which I have mentioned below.
> webpack
keywords if/then/else require v5 option
Hash: 5ba37842c394273b5247
Version: webpack 2.2.0-rc.0
Time: 2330ms
Asset Size Chunks Chunk Names
bundle.js 4.38 kB 0 [emitted] main
style.css 41 bytes 0 [emitted] main
[0] ./src/image_viewer.js 452 bytes {0} [built]
[1] ./src/sum.js 177 bytes {0} [built]
[2] ./assets/big.jpg 235 bytes {0} [built] [failed] [1 error]
[3] ./assets/small.jpg 237 bytes {0} [built] [failed] [1 error]
[4] ./styles/image_viewer.css 41 bytes {0} [built]
[5] ./src/index.js 303 bytes {0} [built]
+ 1 hidden modules
ERROR in ./assets/small.jpg
Module parse failed: I:\Javascript & Angular & Node\webpack\assets\small.jpg Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./src/image_viewer.js 7:13-43
# ./src/index.js
ERROR in ./assets/big.jpg
Module parse failed: I:\Javascript & Angular & Node\webpack\assets\big.jpg Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./src/image_viewer.js 3:11-39
# ./src/index.js
Child extract-text-webpack-plugin:
[1] ./~/css-loader!./styles/image_viewer.css 204 bytes {0} [built]
+ 1 hidden modules
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! jsmodule#1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the jsmodule#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Engraved\AppData\Roaming\npm-cache\_logs\2018-05-27T10_29_34_980Z-debug.log
My webpack version is "webpack": "^2.2.0-rc.0".

I have got the answer for this error. I have researched more and found the issue. It is the little issue by which I had mad.
The issue was that to add space to images extension which I have mentioned in the code. See below the line
test: /\.(jpe?g | png | gif |svg)$/
This line got mad me. You can not give the space between them.
test: /\.(jpe?g|png|gif|svg)$/ - This is the correct.

Related

Why does webpack build global.js?

I'm getting started with webpack, and on my first build I noticed that the output included a default file was included (index 1):
build.js 222 kB 0 [emitted] main
[1] (webpack)/buildin/global.js 509 bytes {0} [built]
[2] ./source/scripts/main.js 105 bytes {0} [built]
+ 4 hidden modules
Why is this file being included? I don't have any dependencies that would require anything close to the amount of code that comes out in my build.js file. I was expecting to have maybe 10 lines of code in the output, instead I have 8000.
I've also noticed some other projects out there don't have this file listed in the output. Is this strictly necessary? I can't even find it in the docs.
For reference, my webpack.config.js file:
'use strict';
module.exports = {
entry: './source/scripts/main.js',
output: {
path: __dirname + '/dist',
filename: 'build.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
I had the same issue. It turned out that I was importing something from node_modules accidentally.
In typescript:
import Util from 'Util';
should have been
import Util from './Util';
since the first one loaded a 'Util' from node modules instead of my local file. The 'exclude: /node_modules/' doesn't seem to matter. I had the equivalent in my tsconfig. Maybe webpack should warn if you import something that's excluded.

Module not found: Error: Can't resolve 'webpack'

I am trying to generate bundle.js using all javascript which I have. Here is command which I used.
> C:\Users\aaa\node_modules\.bin>"C:\Users\aaa\node_modules\.bin\webpack.cmd" "D:\www\webpack.config.js" "D:\www\bundle.js"
bundle.js got generate but build failing. Here is error.
C:\Users\aaa\node_modules\.bin>C:\Users\aa\node_modules\.bin\webpack.cmd D:\www\webpack.config.js D:\www\bundle.js
Hash: 44eb203978bf482447b4
Version: webpack 2.2.1
Time: 94ms
Asset Size Chunks Chunk Names
bundle.js 15 kB 0 [emitted] main
[0] ../webpack/~/node-libs-browser/~/path-browserify/index.js 6.18 kB {0} [bu
ilt]
[1] ../webpack/~/node-libs-browser/~/process/browser.js 5.3 kB {0} [built]
[2] D:/www/webpack.config.js 567 bytes {0} [built]
ERROR in D:/www/webpack.config.js
Module not found: Error: Can't resolve 'webpack' in 'D:\www'
# D:/www/webpack.config.js 2:16-34
Here is my webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
context: path.resolve("www", './src'),
entry: {
app: ['js/index.js', './js/require.js', './js/google-protobuf.js', './js/proto/ByteBufferAB.min.js',
'./js/proto/Long.min.js', './js/proto/control_1.js', './js/proto/data_1.js', './js/proto/data_hmi_1.js',
'./js/proto/main_1.js'],
},
output: {
path: path.resolve("www", './dist'),
filename: 'bundle.js',
}
};
Please give any reference or hint.
Try to change your context and output.path:
context: path.resolve(__dirname, './'),
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
publicPath: '/'
},
Then __dirname will be replaced by your physical path where your files are.
Please check if you have webpack installed globally.
Command to check : webpack -v
Also you should execute webpack build command : webpack --config webpack.config.js --progress --colors.
Please note command should be executed in the same directory where webpack.config.js is present.
Your using local webpack as per your current command.

Using webpack-dev-server and Hot Module Replacement not updating bundle.js with changes to JS or SCSS files

I am using an npm script npm start to run webpack-dev-server --progress --colors --hot --inline --open in the Terminal. My React app loads up fine on the local server. But when I make any SCSS changes for example I see:
webpack: bundle is now INVALID.
Hash: 619812c0fa6ffc42708e
Version: webpack 1.13.3
Time: 343ms
Asset Size Chunks Chunk Names
bundle.js 1.02 MB 0 [emitted] main
0.065f433e5a1a691720c9.hot-update.js 659 bytes 0 [emitted] main
065f433e5a1a691720c9.hot-update.json 36 bytes [emitted]
chunk {0} bundle.js, 0.065f433e5a1a691720c9.hot-update.js (main) 946 kB [rendered]
[249] ./~/css-loader?sourceMap!./~/sass-loader?sourceMap!./src/styles/main.scss 586 bytes {0} [built]
+ 251 hidden modules
webpack: bundle is now VALID.
However, the page doesn't reflect any SCSS or JS changes I make. My bundle.js is not updated at all. However, if i run webpack in another Terminal window my bundle.js updates and then if I refresh my page I can see my changes.
Here is my webpack.config.js:
var webpack = require("webpack");
module.exports = {
entry: "./src/main.js",
output: {
path: "./build/scripts",
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.jsx?$/,
loader: "babel",
exclude: "./node_modules"
},
{ test: /\.scss$/,
loaders: [ "style", "css?sourceMap", "sass?sourceMap" ]
}
],
}
};
Here is my main.js file:
import React from "react";
import ReactDOM from "react-dom";
// CSS
import "./styles/main.scss"
let docBody = "Webpack is doing its thing, with ES2015!!";
document.write(docBody);
Any idea what I'm doing wrong here?

Empty wepback output file with express and react

I'm trying to convert the basic react comment list tutorial to use webpack and things seem to be working, but my output file doesn't ever get populated with anything.
Here's my webpack config:
module.exports = {
context: __dirname + "/app",
entry: "./entry.js",
output: {
path: __dirname + "/public",
filename: "bundle.js",
publicPath: "/ "
},
module: {
loaders: [
{ test: /\.css$/, loader: 'style!css' },
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules|bower_components/,
query: {
presets: ['react']
}
}
]
}
}
Here's some relevant parts of the server supplied by the tutorial that I modified to try and add webpack:
const webpackMiddleware = require('webpack-dev-middleware');
const config = require('./webpack.config');
const app = express();
const compiler = webpack(config);
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(webpackMiddleware(compiler));
When I run the server file it looks like webpack runs, finds my entry.js file and starts building everything the way I would expect:
Server started: http://localhost:3000/
Hash: 8541f0bf4ae3ae4162c1
Version: webpack 1.12.9
Time: 949ms
Asset Size Chunks Chunk Names
bundle.js 680 kB 0 [emitted] main
chunk {0} bundle.js (main) 646 kB [rendered]
[0] ./app/entry.js 249 bytes {0} [built]
[1] ./~/react/react.js 56 bytes {0} [built]
[2] ./~/react/lib/React.js 1.49 kB {0} [built]
[3] ./~/react/lib/ReactDOM.js 3.71 kB {0} [built]
...
[161] ./app/comment-form.js 1.28 kB {0} [built]
webpack: bundle is now VALID.
But my output file bundle.js remains empty. I'm not seeing any errors on the server, the api and public http request are all working appropriately. I think that I've got something messed up in the way that webpack is expecting the node / express stuff to be interacting with the way I'm expecting the front end files to be bundled up together. Help!
Whether through webpack/webpack-dev-server or when you use webpack/webpack-dev-middleware directly in your Express application, the Webpack compiler's file system will be replaced with an in-memory file system.
If you use webpack-dev-middleware, files are resolved from the in-memory file system exclusively. With webpack-dev-server, or when you add the static middleware yourself manually, assets created during compilation are written to the in-memory file system and take precedence over whatever exists in the output directory on disk. This is why you may see that output/foo.png is read from disk, but the empty output/bundle.js is showing fresh, correct chunk content.

phantomjs + webpack not working

npm i -g phantom
/
weak#0.4.1 install C:\Users\muzo0\AppData\Roaming\npm\node_modules\phantom\node_modules\dnode\node_modules\weak
node-gyp rebuild
C:\Users\muzo0\AppData\Roaming\npm\node_modules\phantom\node_modules\dnode\node_modules\weak>if
not defined npm_config_n ode_gyp (node
"C:\DevLibs\nodejs\node_modules\npm\bin\node-gyp-bin\....\node_modules\node-gyp\bin\node-gyp.js"
rebuild ) else (rebuild) Building the projects in this solution one
at a time. To enable parallel build, please add the "/m" switch.
weakref.cc
Creating library C:\Users\muzo0\AppData\Roaming\npm\node_modules\phantom\node_modules\dnode\node_modules\weak\buil
d\Release\weakref.lib and object
C:\Users\muzo0\AppData\Roaming\npm\node_modules\phantom\node_modules\dnode\node_modu
les\weak\build\Release\weakref.exp Generating code Finished
generating code weakref.vcxproj ->
C:\Users\muzo0\AppData\Roaming\npm\node_modules\phantom\node_modules\dnode\node_modules\weak\build
\Release\weakref.node phantom#0.7.2
C:\Users\muzo0\AppData\Roaming\npm\node_modules\phantom ├──
win-spawn#2.0.0 ├── traverse#0.6.6 ├── shoe#0.0.15 (sockjs#0.3.7) └──
dnode#1.2.1 (jsonify#0.0.0, dnode-protocol#0.2.2, weak#0.4.1)
webpack.config.js
module.exports = {
entry: './src/main.js',
output: {
filename: 'dist.js'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel', exclude: /node_modules/ },
{ test: /\.json$/, loader: 'json'}
]
},
target: "node"
};
webpack --hot
Hash: d94ab9a8045078efe92c Version: webpack 1.10.0 Time: 2807ms
Asset Size Chunks Chunk Names dist.js 1.28 MB
0 [emitted] main
+ 180 hidden modules
WARNING in ./~/phantom/~/dnode/~/weak/~/bindings/bindings.js Critical
dependencies: 76:22-40 the request of a dependency is an expression
76:43-53 the request of a dependency is an expression #
./~/phantom/~/dnode/~/weak/~/bindings/bindings.js 76:22-40 76:43-53
WARNING in ./~/phantom/~/shoe/~/sockjs/lib/utils.js Module not found:
Error: Cannot resolve module 'rbytes' in
c:\Users\muzo0\Desktop\new_tele_bot\node_modules\phantom\node
_modules\shoe\node_modules\sockjs\lib # ./~/phantom/~/shoe/~/sockjs/lib/utils.js 7:13-30
WARNING in ./~/phantom/~/dnode/~/weak/~/bindings/README.md Module
parse failed:
c:\Users\muzo0\Desktop\new_tele_bot\node_modules\phantom\node_modules\dnode\node_modules\weak\node_
modules\bindings\README.md Line 2: Unexpected token === You may need
an appropriate loader to handle this file type. | node-bindings |
============= | ### Helper module for loading your native module's .node file | # ./~/phantom/~/dnode/~/weak/~/bindings ^./.*$
node dest.js
module.js:338
throw err;
^ Error: Cannot find module 'c:\Users\muzo0\Desktop\new_tele_bot\dest.js'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
c:\Users\muzo0\Desktop\new_tele_bot>phantomjs
'phantomjs' is not recognized as an internal or external command,
operable program or batch file.
main.js
import phantom from 'phantom';
OS: win 10
npm: 2.7.4

Categories

Resources