Public assets is 404 on prod build (webpack) - javascript

I'm not really familiar with webpack and I have this issue where I can't access my assets on prod - it returns 404
I have this structure:
- repo
- public
- index.html
- images
- animals
- dog.png
- audio
- growl.mp3
- src
- index.js
... other files
Now on my index.js (or other files) I access the images by doing:
import { Loader, utils, Sprite, AnimatedSprite } from 'pixi.js'
loader
.add('images/animals/dog.png' )
.load(async () => {})
... other codes
And this works fine on local, but when I deploy on production It throws
Failed to load resource: the server responded with a status of 404 () - /images/animals/dog.png:1 Failed to load resource: the server responded with
My webpack looks like this:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CircularDependencyPlugin = require('circular-dependency-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
mode: isProd ? 'production' : 'development',
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/',
},
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},
devtool: isProd ? 'cheap-module-eval-source-map' : 'source-map',
devServer: {
hot: true,
watchContentBase: true,
contentBase: [
path.resolve(__dirname, 'public'),
path.resolve(__dirname, 'build'),
],
publicPath: '/',
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
},
},
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: false,
cwd: process.cwd(),
}),
new CopyWebpackPlugin([
{ from: 'public/audio', to: 'audio' },
{ from: 'public/images', to: 'images' },
]),
],
}

Ok, so I figured it out.
It turns out that I just need to make all publicPath to '' (empty string)

Related

Multiple assets emit different content to the same filename index.html

My webpack config gives the following error Multiple assets emit different content to the same filename index.html
when I delete the htmlWebpackPlugin it works, but I won't get any html to show. I'm using Vue.js and my config looks like this:
const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = (env, argv) => ({
mode: argv && argv.mode || 'development',
devtool: (argv && argv.mode || 'development') === 'production' ? 'source-map' : 'eval',
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
node: false,
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
exclude: /\.module\.css$/
}
]
},
resolve: {
extensions: [
'.js',
'.vue',
'.json'
],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': path.resolve(__dirname, 'src')
}
},
plugins: [
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['dist']
}),
new VueLoaderPlugin(),
new HtmlWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [{
from: path.resolve(__dirname, 'static'),
to: path.resolve(__dirname, 'dist'),
toType: 'dir'
}]
})
],
devServer: {
compress: true,
host: 'localhost',
https: true,
open: true,
overlay: true,
port: 9000
}
});
My file structure looks like this
I've looked at Conflict: Multiple assets emit to the same filename but no solution worked for me, are there any other options?
Could it be that Vue loader also emits index.html?
Try:
new HtmlWebpackPlugin({
template: './index.html',
filename: 'anotherFileName.html',
}),

WDS Live Reloading enabled twice

Idk why but all my code runs twice when I run webpack-dev-server(webpack serve)...
my folders path:
dist
src
js
app.js
loadBro.js
scss
main.scss
index.html
List item
here is my webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
app:'./src/js/app.js',
loadBro: './src/js/loadBro.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devtool: 'inline-source-map',
devServer:{
open:true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'index.html',
chunks: ['app', 'loadBro'],
}),
module: {
rules: [
{
test: /\.scss$/,
use: ['style-loader', 'css-loader','sass-loader']
},
],
},
};
you already applied plugins: [new HtmlWebpackPlugin({template: ...}) then no need add <script src="bundle whatever u give here"></script>

Webpack: Issues with /src and /dist files because of the publicPath

When I run webpack-dev-server, with a publicPath of /dist, I'm able to see live-edits for my app (changes to html, styling, js). However, when I compile the app into a production build, the stylesheet and javascript load from /dist/main.css and /dist/main.js instead of from main.css and main.js
The problem seems to be with the publicPath setting. If I remove publicPath, the app compiles with main.css and main.js, but I'm not able to see live edits. However, if I keep publicPath: /dist I can see live edits, but now I get /dist/main.css and /dist/main.js
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/js/app.js',
output: {
filename: 'main.bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist'
}, //js output object
module: {
rules: [
{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
}, //sass to css
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
]
} //babel
]
}, //module object
plugins: [
new MiniCssExtractPlugin({
filename: '[name].min.css',
chunkFilename: '[id].min.css'
}),
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
proxy: 'http://localhost:8080/dist'
}),
new HtmlWebpackPlugin({
template: './src/index.html',
/* minify: {
collapseWhitespace: true
}*/
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', {discardComments: {removeAll: true}}]
},
canPrint: true
})
] //plugins array
}

How to dynamically load an asset (pdf) in an angular app using webpack?

I am trying to load a pdf into my angular app running on webpack dev server using HTML <object> tag with data attribute.
Since the pdf path is generated at run time and is absolute like C:\test.pdf.
It is not loaded into the UI but rather console logs the error -
Not allowed to load local resource: file:///C:/test.jpeg
However the production build of the app which doesn't run on hosting server but as static html works fine. Also, relative path works fine as well.
How can i load the pdf ?
webpack.common.js
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
module.exports = {
resolve: {
extensions: ['.js', '.ts'],
modules: [rootDir, path.join(rootDir, "node_modules")]
},
module: {
rules: [
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[ext]'
},
{
test: /\.(scss|css)$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader",
options: {
includePaths: ["node_modules/"]
}
}
]
}
]},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)#angular/,
path.resolve(__dirname, '../src')
)
]
};
webpack.dev.js
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
commonConfig.entry = {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
};
commonConfig.module.rules.unshift({
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader', 'angular-router-loader']
});
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: path.resolve(rootDir, 'dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[name].chunk.js'
},
plugins: [
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});
You could tell the devServer from where to serve files.
devServer: {
historyApiFallback: true,
stats: 'minimal',
contentBase: ['./dist', 'C:\\']
}
Then you can load your file with <... src="/file_name.ext" ... />
But I would not recommend adding C:\ as contentBase. If you have the possiblity, define another output directory for your generated PDF.

Having some trouble with my webpack config, and I think I am confused by the directory structure I am using

I am trying to learn webpack, and I think I am confused by __dirname and getting the right entry file to work. Basically, the file I want to use is in app/index.js, and my server.js and webpack.config.js are in config/.
I had this working fine when I had kept server.js and webpack.config.js in the root, but I want to move it into a config folder, and I also added an app folder instead of keeping the contents of the app as it is right now in the root.
I have the following file structure:
.
|++[app]
|----[actions]
|----[modules]
|----[reducers]
|----[store]
|----index.html
|----index.js
|--[config]
|----server.js
|----webpack.config.js
|--[node_modules]
|--package.json
I have the following in my server.js:
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var config = require('./webpack.config');
var path = require('path');
var app = new (require('express'))();
var port = 9001;
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.resolve(__dirname) + 'app/index.html');
});
app.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info('started on localhost://%s.', port);
}
});
And the webpack.config.js:
var webpack = require('webpack');
var path = require('path');
var autoprefixer = require('autoprefixer');
var isProd = process.env.NODE_ENV === 'production';
module.exports = {
devtool: isProd ? null : 'source-map',
entry: 'app/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
root: path.resolve(__dirname, 'app'),
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'react-hot',
'babel'
],
include: path.join(__dirname, ''),
exclude: /node_modules/
},
{
test: /\.(png|jpg)$/,
loader: 'file-loader?name=img/[name].[ext]'
},
{
test: /\.scss$/,
loader: 'style!css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]!postcss!sass'
}
]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin()
],
postcss: [
autoprefixer({ browsers: ['last 3 versions'] })
]
};
If it helps, the following is my current webpack config
import path from 'path';
import webpack from 'webpack';
export default {
target: 'node',
node: {
// prevents webpack from overwriting the values from node
// https://github.com/webpack/webpack/issues/1599
__dirname: false,
__filename: false
},
devtool: 'source-map',
resolve: {
root: path.resolve(__dirname + '/app'),
extensions: ['', '.js']
},
entry: {
server: './app/app'
},
output: {
path: path.join(__dirname + '/../dist'),
filename: '[name].bundle.js',
libraryTarget: 'commonjs'
},
// prevents node_modules from being bundled by webpack
externals: [/^(?!\.|\/).+/i,],
module: {
loaders: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /(node_modules|dist)/,
cacheDirectory: 'webpack-cache',
query: {
presets: ['es2015'],
plugins: [
'transform-runtime',
'transform-async-to-generator'
]
}
}]
}
}

Categories

Resources