Webpack Build Can't Find CSS or JS Bundles - build

When trying to run my build script for the first time, I noticed that while the files were created, if I try to open the index.html file in the build directory it can't find any of the CSS or JS bundle files, even though they're in the build directory. Here's my webpack.config:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const extractSass = new ExtractTextPlugin({
filename: '[name].[contenthash].css',
disable: process.env.NODE_ENV === 'development'
});
const VENDOR_LIBS = [
'react',
'react-dom',
'react-router',
'react-router-dom'
];
module.exports = {
entry: {
bundle: ['babel-polyfill', './src/index.js'],
vendor: VENDOR_LIBS
},
output: {
path: path.join(__dirname, 'build'),
publicPath: '/',
filename: '[name].[chunkhash].js'
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: [path.resolve(__dirname, 'src')],
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'stage-0', 'react']
}
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract([
'css-loader',
'postcss-loader',
'sass-loader'
])
},
{
test: /\.png$/,
use: [
{
loader: 'url-loader',
options: { limit: 40000 }
},
{
loader: 'image-webpack-loader',
query: { bypassOnDebug: true }
}
]
}
]
},
devServer: {
historyApiFallback: true
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [autoprefixer]
}
}),
extractSass
]
};
And my index.html file in the build folder:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="/bundle.9e0f7c3719625da97504e3ec5c2054db.css" rel="stylesheet"></head>
<body>
<div id="entry"></div>
<script type="text/javascript" src="/manifest.a2844a6ed8a5cd15d1a5.js"></script>
<script type="text/javascript" src="/vendor.14bbb1b3abf7a67a5307.js"></script>
<script type="text/javascript" src="/bundle.1ef0a652c0808bca139d.js">
</script></body>
</html>
The error I get in the browser dev tools is Failed to Load Resource for each of my 3 JS bundle files and my 1 CSS file. If I remove the "/" in front of each of the filenames in the index.html file, those errors go away but then I get another error that it can't find a specific .png file in the build, which is also in the build folder.
I'm using webpack 2.6.1
If I can provide any further info please let me know - kinda new at asking questions here.

Change your webpack config to:
module.exports = {
output: {
publicPath: ''
}
}

Related

Next-AUTH UNTRUST_HOST_ERROR on AWS Amplify

Deployed NextJS app on AWS Amplify
I am getting untrust host in my CloudWatch logs.
Can someone help?
[next-auth][error][UNTRUST_HOST_ERROR]
URL: https://master.dtzbr8sfj0q7k.amplifyapp.com/
I have added this domain in my Cognito allowed callbacks.
package.json
"next": "13.0.7",
"next-auth": "^4.18.6",
Build Settings
version: 1
applications:
- frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- npm run build
- COGNITO_CLIENT_ID=${COGNITO_CLIENT_ID}
- COGNITO_CLIENT_SECRET=${COGNITO_CLIENT_SECRET}
- COGNITO_DOMAIN=${COGNITO_DOMAIN}
- JWT_SECRET=${JWT_SECRET}
- NEXTAUTH_URL=${NEXTAUTH_URL}
artifacts:
baseDirectory: .next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
appRoot: client
/pages/api/[...nextauth].js
import NextAuth from "next-auth/next";
function CognitoProvider(options) {
return {
id: "cognito",
name: "Cognito",
type: "oauth",
wellKnown: `${options.issuer}/.well-known/openid-configuration`,
idToken: true,
profile(profile) {
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture,
};
},
options,
};
}
export default NextAuth({
providers: [
CognitoProvider({
clientId: process.env.COGNITO_CLIENT_ID,
clientSecret: process.env.COGNITO_CLIENT_SECRET,
issuer: process.env.COGNITO_DOMAIN,
}),
],
secret: process.env.JWT_SECRET,
callbacks: {
jwt({ token, account, profile }) {
if (account) {
console.log("Account exists");
// modify token
token.role = profile["cognito:groups"];
}
return token;
},
session({ session, token }) {
if (session.user) {
// modify session
session.user.roles = token.role;
}
return session;
},
},
});
/index.js
import Head from "next/head";
import App from "../components/App/App";
import { useSession, signIn, signOut } from "next-auth/react";
export default function Home() {
const { data: session } = useSession();
if (session) {
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<App />
</>
);
}
return (
<>
Not signed in <br />
<button
onClick={() => {
e.preventDefault();
signIn("cognito", {
callbackUrl: process.env.NEXTAUTH_URL,
});
}}
>
Sign in
</button>
</>
);
}
Any Help would be appreciated
I had the same problem today and I found this solution that worked for me:
I had to edit the amplify.yml in build settings and set env variables inside a .env file as below:
version: 1
frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- echo "NEXTAUTH_URL=$NEXTAUTH_URL" >> .env
- echo "JWT_SECRET=$JWT_SECRET" >> .env
- npm run build
artifacts:
baseDirectory: .next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
I had to do it for all of my environment variables to allow my Next.js application to access them.
Hope it helped.
Make sure you have configured NEXTAUTH_URL environment variable correctly on AWS Amplify.
I checked your website, and I see this error:
CLIENT_FETCH_ERROR
On NextAuth.js documentation,
Here's a similar case:
How to solve client fetch error for next-auth authentication
Update
Sorry for the late reply. These links might give you a little more information about the issue.
Similiar Case
Environment Variables User Guide on AWS Amplify

Module Federation Not working with dynamic hooking the remote in webpack.config.js

I have module federation setup and working fine when I load the remotes upfront in index.html
Below works
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://localhost:8002/remoteEntry.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
host webpack
{
name: "home",
library: {type: "var", name: "home"},
filename: "remoteEntry.js",
remotes: {
nav: "dashboards",
},
shared: ["react", "react-dom"],
}
remote webpack
{
name: "dashboards",
library: {type: "var", name: "dashboards"},
filename: "remoteEntry.js",
remotes: {},
exposes: {
Header: "./src/Header",
},
shared: ["react", "react-dom"],
}
However this loads the JS File upfront which is undesireable. I was following examples where the library is dynamically loaded in webpack... Here is what I want to do
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<div id="root"></div>
</body>
</html>
host webpack
{
name: "app-shell",
filename: "remoteEntry.js",
remotes: {
dashboards: "dashboards#http://localhost:8002/remoteEntry.js",
},
}
remote webpack
{
name: "dashboards",
filename: "remoteEntry.js",
remotes: {},
exposes: {
Header: "./src/Header.jsx",
},
}
I get error on the host app
Uncaught syntax error; Invalid or unexpected token:
module.exports = dashboards#http://localhost:8002/dist/remoteEntry.js;
You're Remote Webpack exposes object is incorrect. You're missing the ./ in front of Header. Replace with this:
"./Header": "./src/Header.jsx"
Also, if that doesn't work, try removing the library section:
library: {type: "var", name: "dashboards"}
I think this changes the remoteType from var to script, which apparently helps.

How to extract css from multiple components into a single file with vue cli 3?

This is what I have tried in my vue.config.js:
module.exports = {
configureWebpack: {
optimization: {
splitChunks: {
cacheGroups: {
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
enforce: true,
},
},
},
},
},
css: {
sourceMap: devMode,
extract: {
filename: 'main.css',
},
},
};
I'm getting multiple css files in my output dir and I would like to merge/optimise all them into a single file. I have multiple chunks created by dynamic import and am not sure if that's the cause.
In my old webpack template with previous CLI I used extract-text-webpack-plugin for the job and it worked.
I found some discussions in the issues below but at the time of this question no solutions yet.
mini-css-extract-plugin #41
mini-css-extract-plugin #52

ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src when use webpack4.2.0

when i use webpack4.2.0, play 'run start', show errors follow:
WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.
ERROR in multi (webpack)-dev-server/client?http://localhost:8001 ./src
Module not found: Error: Can't resolve './src' in '/Users/xudengwei/projects/xudengwei/myOpenGithub/angular5-scaffold'
# multi (webpack)-dev-server/client?http://localhost:8001 ./src
ℹ 「wdm」: Failed to compile.
#
my configure as follow:
webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/app/main.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader"
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
inject: true
})
]
};
webpack.dev.js:
var path = require('path');
var webpackMerge = require('webpack-merge');
var commonConfig = require('./webpack.common.js');
module.exports = webpackMerge(commonConfig, {
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
module: {
rules: []
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
inject: true
})
],
devServer: {
devServer: {
contentBase: './dist'
},
}
});
someone knows the reason?thanks
I also just get this error like you got and its was solved when i specify webpack config file. Try to add --config when you run webpack-dev-server. Ex. webpack-dev-server --config webpack.dev.js
what command did you run in the terminal? It looks to me like you used run start ./src and so it's complaining that it can't find the location ./scr
Try just running run start with no additional arguments. That did the trick for me

Webpack not compiling files on Heroku

I want to use Webpack to compile files for my Django app on Heroku, and am using webpack-bundle-tracker to keep track of the modules created in webpack-stats.json. When I run webpack locally, it compiles all the files and bundles them into the output directory, no problem. But when I run webpack on Heroku, it shows me that all the chunks were emitted, but none of the files appear in the output directory. When I check the content of webpack-stats.json it always says "status" : "compiling".
Here's the content of my webpack.config.js.
var path = require('path')
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
module.exports = {
context: __dirname,
entry: './assets/js/index',
output: {
path: path.resolve('./assets/bundles/'),
filename: '[name].js',
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
loaders: [
{ test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react']
}
}
]
},
resolve: {
modulesDirectories: ['node_modules', 'bower_components'],
extensions: ['', '.js', '.jsx'],
},
}
I want webpack to bundle my assets the same way on heroku as it does on my local machine. How can I accomplish that?