Webpack publicPath don't work - javascript

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.

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 tell web pack to use external js file url without freezing in in bundle?

There is a simple task:
I want to try making a Google Chromecast receiver app (which is SPA). Google Chromecast SDK (cast SDK) requires their framework to be on external url. Also this framework creates global cast object.
What is the correct way of creating this webpack application?
The targets I want to achieve:
Build index.html with HtmlWebpackPlugin
Develop using import this framework (import cast from ???)
Avoid bundling it (probably using externals)?
Ensure cast object created by this js file is global (ProvidePlugin?)
Add <script src="http://cdn....js"></script> into HTML created by HtmlWebpackPlugin
For now I am trying to setup simple app, and I got stuck on last step - adding <script> tag to output html, but I'm sure that there are mistakes I've done on prev steps.
Could you help guiding me through this process?
My current webpack.config.js is:
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
module: {
rules: [
{ test: /\.svg$/, use: 'svg-inline-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ] },
{ test: /\.(js)$/, use: 'babel-loader' }
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
scriptLoading: 'defer',
hash: true,
}) ,
new webpack.ProvidePlugin({
cast: path.resolve(path.join(__dirname, 'src/cast_receiver_framework'))
})
],
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
devServer: {
compress: false,
disableHostCheck: true
},
externalsType: 'script',
externals: {
cast_receiver_framework: ['//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js', 'cast']
}
}
To solve your last step you can use the template param of HtmlWebpackPlugin to customize your template.
By default HtmlWebpackPlugin will inject bundled modules at the end of the <body>.
Check the documentation if you need further customization.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Whatever else you might need -->
</head>
<body>
<div id="your-mount-point-id"></div>
<script src="http://cdn....js"></script>
</body>
</html>
webpack.config.js
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "path/to/index.html"),
scriptLoading: 'defer',
hash: true,
})
],

Cannot find file from a webpack build

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.

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 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