No output in console chrome inspect element (Webpack configuring ) - javascript

Hello I am unable to see output in my chrome inspect element. Following are my files.
Output
Webpack.config.js
const path = require("path");
module.exports = {
entry: ["./src/js/index.js"],
output: {
path: path.resolve(__dirname, "dist/js"),
filename: "bundle.js"
}
};
PACKAGE JSON
{
"name": "forkify",
"version": "1.0.0",
"description": "forkify project",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production"
},
"author": "Gaurav Yadav guided by Jonas",
"license": "ISC",
"devDependencies": {
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10"
}
}
TEST.JS
console.log("Export data");
export default 23;
INDEX.JS
// Global app controller
import num from "./test";
console.log(`${num} from test`);
dist/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>test</title>
</head>
<body>
<script>
src = "js/bundle.js";
</script>
</body>
</html>
My project folder name is FORKIFY. There are three subfolders dist, src , nodemodules and three files pacakage-lock.json, pacakage.json, webpack.config.js. Directory image dir.
Please let me know why my console in empty ?
I was following this video to code
https://www.youtube.com/watch?v=sBEryysS1Tg&list=PL15NLmjJalxydhO9orvXv_yvgZEfrDQvX&index=127
Where is the problem and in which file ??
Do i need to change my webpack config file ?

Your folder structure is incorrect.
const path = require("path");
module.exports = {
entry: ["./src/js/index.js"],
output: {
path: path.resolve(__dirname, "dist/js"),
filename: "bundle.js"
}
};
The dist folder will get created when you run the webpack command and you have mentioned your index.html file is present in the dist folder.
Place your index.html file at the root level of your project. Also, if js is folder within dist, then add slash to treat as a directory i:e path: path.resolve(__dirname, "dist/js/")
Appropriate Folder Structure
node_modules
src
-js
- index.js
index.html
package.json
webpack.config.js
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist/js/')
},
watch: true
}
// index.js
console.log('logging');
// index.html
<h1>WebPack works!!</h1>
<script src="dist/js/bundle.js"></script>
Run command webpack, which will create bundle.js file within dist/js/ folder and then open your index.html file in the browser.

Related

ERR_FILE_NOT_FOUND bundle.js

I'm starting to use webpack, and I did a tiny project to try, but I'm finding an error that I don't know how to fix. When I run my index.html, it says that can't find bundle.js. I think is something wrong with the path, but I'm not sure. Hope someone can help me!
This is my structure
prueba1
node_modules
build
bundle.js
src
app.js
index.html
messages.js
style.css
package.lock.json
package.json
webpack.config.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Document</title>
<link href="style.css" />
</head>
<body>
<button id="connect">Conectar</button>
<script src="bundle.js"></script>
</body>
</html>
package.json
{
"name": "prueba1",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^5.51.1"
},
"devDependencies": {
"webpack-cli": "^4.8.0"
}
}
webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/app.js",
output: {
filename: "bundle.js",
path: __dirname + "/build",
},
};
The problem is that your index.html and your bundle.js are in different directories (src and build). You could simply move your index.html to build and it will work.
Or you let webpack do that work with the copy-webpack-plugin (https://www.npmjs.com/package/copy-webpack-plugin): install it using npm install copy-webpack-plugin --save-dev, and add this to your webpack.config.js:
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{ from: "src", to: "build" }
],
}),
],
};

How can I get my JS errors in chrome to show the correct line numbers?

I believe my webpack config may be the culprit or my npm run dev script, but I'm not sure what the issue is. When I run my app in dev mode I'm getting error messages like:
Uncaught TypeError: this.props.contacts.map is not a function
at ContactList.renderList (ContactList.jsx:46)
at ContactList.render (ContactList.jsx:61)
at finishClassComponent (react-dom.development.js:14695)
at updateClassComponent (react-dom.development.js:14650)
at beginWork (react-dom.development.js:15598)
at performUnitOfWork (react-dom.development.js:19266)
at workLoop (react-dom.development.js:19306)
at HTMLUnknownElement.callCallback (react-dom.development.js:149)
at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
at invokeGuardedCallback (react-dom.development.js:256)
But my ContactList.jsx is only 36 lines long.
My webpack config:
module.exports = {
mode: 'development',
entry: './client/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-react']
}
}
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
}
};
scripts:
"scripts": {
"start": "npx webpack --mode=development && node server/server.js",
"build": "webpack --mode=development",
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --config ./webpack.config.js --mode development"
}
One other important detail, I think, is that I'm serving my front-end app via an express server. It is that front-end application I'm trying to debug. Can I package it in a dev mode or something like this?
I'm serving an html and bundle.js file. The HTML just references the endpoint where I'm serving my react application.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>The Minimal React Webpack Babel Setup</title>
</head>
<body>
<div id="app"></div>
<script src="./dist/bundle.js"></script>
</body>
</html>
My app is here:
https://github.com/int-a/contacts/tree/split-first-last-name
Try to add devtool in webpack config ,like 'devtool:"#source-map"'

npx webpack command cannot find module webpack.config.js

I'm following the official Webpack getting started guide and I get an error on the Using a Configuration section. It says to create a webpack.config.js file with:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
I then run the following command:
npx webpack --config webpack.config.js
The error I get is:
Cannot find module '/Users/Documents/Web_Development/tone/webpack.config.js'
The guide does not seem to give any ideas of what could be wrong here. Also my code editor is telling me there is an error with const path = require('path'); saying "Expected a JSON Object, array or literal;
My Directory structure:
webpack.config.json
package.json.lock
package.json
node_modules/
dist/
index.html
main.js
src/
index.js
package.json:
{
"name": "tone",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"webpack": "^4.29.3",
"webpack-cli": "^3.2.3"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
The solution was to change the webpack.config.json file to webpack.config.js.
You have to make sure that the webpack.config.js file is in the root of your project.

How after building the dist folder in Webpack, move the bundle.js and css file into the statics folder?

When I run my npm run build or npm run build-dev
It creates the index.html and manage2.bundle.js and manage2.css files in the root. I need to move those files into the static directory.
So the generated index.html below will actually work, with the correct paths:
<!doctype html>
<html lang="en">
<head>
<title>Manage2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="The TickerTags backend manage app">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300|Source+Sans+Pro:200,600" rel="stylesheet">
<link rel="icon" type="image/x-icon" href="static/favicon.ico">
<link href="/static/manage2.css" rel="stylesheet"></head>
<body>
<div id="manage2"></div>
<script type="text/javascript" src="/static/manage2.bundle.js"></script></body>
</html>
How is this acomplished? webpack.config below
const fs = require('fs');
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const environment = process.env.NODE_ENV;
const stream = fs.createWriteStream("src/services/environment.js");
stream.once('open', function(fd) {
stream.write('const env = "'+environment+'"\n');
stream.write('export default env');
stream.end();
});
module.exports = {
context: src,
entry: [
"./index.js"
],
output: {
path: dist,
filename: "manage2.bundle.js",
publicPath: '/static/',
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: ["css-loader", "sass-loader"],
publicPath: dist
})
}
]
},
devServer: {
hot: false,
quiet: true,
publicPath: "",
contentBase: path.join(__dirname, "dist"),
compress: true,
stats: "errors-only",
open: true
},
plugins: [
new HtmlWebpackPlugin({
template: "index.html"
}),
new ExtractTextPlugin({
filename: "manage2.css",
disable: false,
allChunks: true
}),
new CopyWebpackPlugin([{ from: "static", to: "static" }])
]
};
// new webpack.DefinePlugin({ env: JSON.stringify(environment) })
My npm scripts
"scripts": {
"dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
"prod": "NODE_ENV=production webpack-dev-server -p",
"build": "NODE_ENV=production webpack -p",
"build-dev": "NODE_ENV=production webpack -d",
This config is saving the *.js and *.css to the static folder.
output: {
// the output bundle
filename: '[name].[hash].js',
// saves the files into the dist/static folder
path: path.resolve(__dirname, 'dist/static'),
// set static as src="static/main.js as relative path
publicPath: 'static/'
},
With the HtmlWebpackPlugin you can generate a html file from a template. With this config in the Webpack plugins section the index.html is saved to the dist. folder with the correct path to the *.js and *.css.
plugins: [
// is only working with npm run build
new HtmlWebpackPlugin({
title: '',
// save index.html one director back from the output path
filename: '../index.html',
template: 'index.template.ejs',
hash: false
}),
],
index.template.ejs
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
</head>
<body>
</body>
</html>
Results in
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>
</title>
<link href="static/main.css" rel="stylesheet">
</head>
<body>
<script type="text/javascript" src="static/main.js"></script>
</body>
</html>
Your output.path is incorrect. It should be path.resolve(__dirname, 'dist', 'static').
And since now your output.path points to dist/static, set publicPath back to /.

ReactJS: Unexpected Token <

TL;DR: Why am I getting the error with my code? Previous question is different (online vs desktop) and it's answers don't work for me.
Complete code here
Based on code more or less originating here (I'm not quite to the end of the "lesson"
Question: Following this "intro to ReactJS". The walkthrough has Webpack/Babel setup. It runs with plain JS, but when I switch to JSX it chokes. This is similar to this question, but none of those answers seem to work. Main difference: Web Playground vs locally on my box?
The end of the video I'm working on leads to this code - although, I'm only 3/4 of the way through so parts aren't included yet. So, I've dialed it back into this fork with my edits (Sorry if I've butchered forking and pushing my changes...)
Notes: The BEFORE and AFTER is the only things I've changed. It works with javascript/jquery - but not with JSX. I found a couple typos, case errors (thisItem vs thisitem) and some items that shouldn't have been there (brackets removed).
I've changed "my" typed out version to more closely match "their" version (Hello instead of HelloWorld) and made other minor changes... same error.
The biggest remaining changes I see other than some spacing issues is versions - minor version bumps from the recorded class.
My Code:
.babelrc
{ "presets": [ "react" ] }
package.json
{
"name": "github-battle",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server",
"production": "webpack -p"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^0.14.7",
"react-dom": "^0.14.7"
},
"devDependencies": {
"babel-core": "^6.6.0",
"babel-loader": "^6.2.4",
"babel-preset-react": "^6.5.0",
"html-webpack-plugin": "^2.9.0",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
}
}
webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin')
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
})
module.exports = {
entry: [
'./app/index.js'
],
output: {
path: __dirname + '/dist',
filename: "index_bundle.js"
},
module: {
loaders:[
{ test: /\.js$/,include: __dirname + '/app',loader: "babel-loader" }
]
},
plugins: [HtmlWebpackPluginConfig]
}
app\index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Github Battle</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>
<body>
<div id="app"></div>
</body>
</html>
app\index.js BEFORE
var app = document.getElementbyid('app')
app.innerHTML = 'Hello
app\index.js AFTER
var React = require('react');
var ReactDOM = require('react-dom');
var HelloWorld = React.createClass({
render: function () {
return <div> Hello World </div>
}
});
ReactDOM.render(
<HelloWorld />,
document.getElementById('app')
);
Result:
> B:\Users\Chris\react-js\React-Fundamentals>npm run production
> gh-battle#1.0.0 production B:\Users\Chris\react-js\React-Fundamentals
> webpack -p
Hash: 21e367e251c35209471c
Version: webpack 1.12.14
Time: 375ms
Asset Size Chunks Chunk Names
index_bundle.js 289 bytes 0 [emitted] main
index.html 305 bytes [emitted]
[0] multi main 28 bytes {0} [built] [1 error]
[1] ./app/index.js 0 bytes [built] [failed]
ERROR in ./app/index.js
Module parse failed: B:\Users\Chris\react-js\React-Fundamentals\app\index.js Line 6: Unexpected token <
You may need an appropriate loader to handle this file type.
| var Hello = React.createClass({
| render: function () {
| return <div> Hello ReactJS World! </div>
| }
| });
# multi main
Child html-webpack-plugin for "index.html":
+ 3 hidden modules
B:\Users\Chris\react-js\React-Fundamentals>
webpack.config.js #2: Same rror
var HtmlWebpackPlugin = require('html-webpack-plugin');
...
module.exports = {
...
module: {
loaders: [
{test: /\.js$/, include: __dirname + '/app', loader: "babel-loader"}
],
query: {
presets: ['react']
}
},
plugins: [HTMLWebpackPluginConfig]
};
You need to rename index.js to index.jsx.
silly question: have you tried removing the square brackets in the "entry" declaration?
module.exports = {
entry: './app/index.js',
output: {
path: __dirname + '/dist',
filename: "index_bundle.js"
},
module: {
loaders:[
{
test: /\.js$/,
include: __dirname + '/app',
loader: "babel-loader"
}
]
},
plugins: [HtmlWebpackPluginConfig]
}
From your second webpack config file, query should be inside the babel loader object.
module: {
loaders: [
{
test: /\.js$/,
include: __dirname + '/app',
loader: "babel-loader",
query: {
presets: ['react']
}
}
]
}
Don't forget to install the babel-preset-es2015 plugin if you plan on using es6.
Working Code here
After banging my head against the wall (which, honestly, helps beat the knowledge in - so it isn't all for naught)... I've made a couple minor changes and seem to be successful now:
changed .js to .jsx - I like the "explicit" acknowledgement that these aren't plain ole js. (not required I think, more style)
I've removed the babelrc file and moved query into webpack.config... seems to be easier to compartmentalize things in a single file. this actually isn't working for me... se'la'vie
The "solution" seems to be the __dirname + '/dir' changed into path.join(...) - with var path = require('path') actually included. I'll research (and ask a new question if I don't find one) how/why those two aren't equal, but I can only assume it has something to do with differing operating systems (Windows 10x64 for me).
EDIT:: Just some random poking, but include:__dirname + 'app', fails... as does '\app', '\app\', '/app', '/app/'... no clue why, but path.join(...) works.
Also worth noting, is that template: __dirname + '...', seems to work, but not the parts below it. Filename vs directory, so again not sure of the difference.
webpack.config.js
var path = require('path');
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: [
'./app/index.jsx'
],
output: {
path: path.join(__dirname, '/dist'),
filename: "index_bundle.js"
},
module: {
loaders: [{
test: /\.jsx?$/,
include: path.join(__dirname, '/app'),
loader: "babel-loader"},
]
},
plugins: [HTMLWebpackPluginConfig]
};
index.jsx
var React = require('react');
var ReactDOM = require('react-dom');
var HelloWorld = React.createClass({
render: function () {
return <div> Hello ReactJS World! </div>
}
});
ReactDOM.render(
<HelloWorld />,
document.getElementById('app')
);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Github Battle</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div id="app"></div>
<script src="index_bundle.js"></script></body>
</html>

Categories