Cannot find file from a webpack build - javascript

I am new to webpack and currently trying to go through some demos. However it seems that my server cannot find the file referenced from index.html file.
I am using http-server, and this is the index.html page:
<html>
<head>
<title>Page title</title>
</head>
<body>
<div id="app"></div>
<script src="../build/js/bundle.js"></script>
</body>
</html>
...and my webpack.config.js file:
var path = require("path");
module.exports = {
context: path.resolve("src"),
entry: "./index.js",
output: {
path: path.resolve("build/js/"),
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
resolve: {
extensions: [".js", ".es6"]
}
};
Currently I am trying to setup the following file structure:
build
js
bundle.js
src
js
App.js
index.js
public
index.html
After running webpack and starting the server I get a 404 error, stating that bundle.js could not be found.

Related

running page specific setup functions while using web pack - "does not provide an export named 'init_home'"

I have a structure like this, with js files i have bundled with web pack. (all simplified for readability)
home.html
main.bundle.js
home.html
<html>
<head>
<script type="module" src="main.bundle.js"></script>
</head>
<body>
</body>
</html>
inside the src js it would look like this
src.js
import {some-imports} from this.js
window.addEventListner("load", ()=>{
# page load code for ALL pages
})
function init_home(){
#home page init code
}
function init_contact(){
#contact page init code
}
export {init_home, init_contact}
how is the prefered way to call these init functions on each page?
I have tied adding this script tag at the bottom of each page with no luck
<script type="module">
import {init_home} from './static/deploy/main.bundle.js'
init_home()
</script>
I keep getting errors like this.
The requested module './static/deploy/main.bundle.js' does not provide an export named 'init_home'
also is it correct that i am trying to import the same js file twice?
webpack.config.js (just incase)
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');
module.exports = {
plugins: [
new CleanWebpackPlugin()
],
entry: {
main: path.resolve(__dirname, './js/fire.js'),
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'deploy')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
]
},
}

How to use js library generated with webpack in a simple html page

So I created a javascript library using the following starter project https://github.com/a-tarasyuk/webpack-typescript-babel, which uses webpack, typescript and babel.
I change the webpack config to generate a library using UMD so I can use the library in the browser and server.
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, 'src'),
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'lib'),
library: 'mylib',
libraryTarget: 'umd',
globalObject: `(typeof self !== 'undefined' ? self : this)`,
umdNamedDefine: true,
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json']
},
module: {
rules: [{ test: /\.(ts|js)x?$/, loader: 'babel-loader', exclude: /node_modules/ }],
},
plugins: [
new ForkTsCheckerWebpackPlugin(),
new CleanWebpackPlugin()
]
};
Then when I build the library, I have the index.js file in the lib directory
When I drop the index.js in a simple html. how can I use the Value class in the project? I tried the following but it throws a Uncaught ReferenceError: Value is not defined
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webpack App</title>
</head>
<body>
<script type="text/javascript" src="index.js">
</script>
<script>
var val = new Value();
</script>
</body>
</html>
Thanks
I found a solution but I'm not sure if that is the expected behavior. When I inspected the window object the following code works
<script>
var p = new window.mylib.Value();
p.setValue(1000);
console.log(p.getValue());
</script>
So I guess webpack is adding the library to the window object when running in the browser ?
UPDATE:
I think it's because of the globalObject is set to 'this' which will mount the library to the window when in browser.

Cannot GET / with webpack-dev-server

How come I am getting Cannot GET / in my browser? I think it is because my webpack-dev-server does not have a route to GET the bundled files.
devServer/server.js
import config from '../../webpack.config';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import open from 'open';
// template! https://github.com/webpack/webpack-dev-server/blob/master/examples/node-api-simple/server.js
const compiler = webpack(config);
const server = new WebpackDevServer(compiler, {
contentBase: '../dist/',
stats: {
colors: true
}
});
server.listen(3000, '127.0.0.1' ,err => {
if (err) {
console.log(err);
} else {
console.log('Dev Server listening on port 3000!\n');
open("http://localhost:3000");
}
});
webpack.config.js
import webpack from "webpack";
export default {
entry: [
"./app/index"
],
devtool: "inline-source-map",
output: {
path: __dirname + "/app/dist/", // Note: Physical files are only output by the production build task `npm run build`.
publicPath: "/",
filename: "bundle.js"
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
module: {
rules: [
{ test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}}
]
}
};
Project structure
On successful build a folder dist will be created inside the app folder which currently is not there.
Once the folder is created you can try by directly hitting the file path
http://localhost:3000/app/dist/yourfile
You can access your page via localhost:3000
When you access this path webpack dev server is searching for an index.html file to serve (like any other webserver). It can not find an index.html file because you have no index.html file. The index.html file is served from the static directory, which you have defined via property contentBase: '../dist/',.
but as I see you have no directory named dist and you have no index.html in this directory.
Your script is served from the public path, that is / in your config, so you have to reference this in your index.html
Solution:
Create directory dist and put an index.html file there with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="/bundle.js"></script>
</body>
</html>
For more information read here:
https://webpack.github.io/docs/webpack-dev-server.html

Webpack publicPath don't work

I have a demo like this:
my webpack config:
module.exports = {
entry: './app.js',
output: {
filename: 'bundle.js',
path: './build',
publicPath: 'http://localhost:3000/'
},
module: {
rules: [{
test: /static\.html/,
use: 'file-loader'
}, {
test: /\.png/,
use: 'file-loader?name=[name].[ext]'
}, {
test: /\.css/,
use: 'file-loader?name=[name].[ext]'
}],
},
resolveLoader: {
modules: ['node_modules'],
}
}
this is my entry app.js:
import './static.html';
import './img.png';
import './index.css';
static.html:
<!DOCTYPE html>
<html>
<head>
<title>static</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="./index.css">
</head>
<body>
<img src="./img.png">
</body>
</html>
when i run npm run build, i got a build folder. I think the build/static.html should be
<img src="http://localhost:3000/img.png">
<link href="http://localhost:3000/index.css">
But, actually the build/static.html is the same as static.html. Both of the src of img and the href of link are not changed.
Any one knows why?
====
I have known the answer. Webpack publicPath just work for output file. So just the url in the bundle.js will be replaced.
The webpackHtmlPlugin will not resolve this problem, because this plugin will generate a html page with a script links to the output bundle.js that I don't need it.
To resolve this problem, I have wrote a custom loader to transform the html page output by the file-loader dynamicly.
The file-loader would not change the file. If you want a html file with the publicPath added, you should use html-webpack-plugin.

Webpack for React doesn`t work

I am just start React and have finished codecademy courses and several other on youtube. I decide to configure my local machine for react. I ve started with webpack & webpack-dev-server. And here I get mistake.
Here is mistake screenshot
Also Here is my files tree
Here is my webpack.config.js:
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://127.0.0.1:8080/',
'webpack/hot/only-dev-server',
'./src'
],
output: {
path: path.join(__dirname, 'public'),
filename: "bundle.js"
},
resolve: {
modulesDirectories: ['node_modules', 'src'],
extensions: ['', '.js']
},
module: {
loader: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?presets[]=react,presets[]=es2015']
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
My index.html:
<!DOCTYPE html>
<html>
<head>
<title>React ToDos App</title>
</head>
<body>
<div id="app" />
<script src="bundle.js"></script>
</body>
</html>
And index.js:
let message = 'Hello from entry message';
console.log(message);
Thanks for any help.
I see two issues in your code:
The name of js bundle should be the same in html and in webpack – you use ready.js in webpack config and bundle.js in your html.
On your screenshot you have a typo and name of webpack config is webpack.congig.js, but it should be webpack.config.js (that is used by default by webpack-dev-server)
In your webpack config you're setting the output filename as ready.js and in your HTML your are looking for bundle.js. This is the reason for the error. Give a same name in both the places.
<!DOCTYPE html>
<html>
<head>
<title>React ToDos App</title>
</head>
<body>
<div id="app" />
<script src="ready.js"></script>
</body>
</html>

Categories

Resources