Ant Design - Works if built but not with Webpack Dev Server - javascript

I have a new React project and would like to use
Ant Design Components
The components already work, but only if I build the whole project file. So with yarn build it works, but the webpack dev server I created does not serve the CSS.
The CSS won't be loaded. Error in console:
Refused to apply style from 'http://127.0.0.1:3999/~antd/dist/antd.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Already had a look at Stylesheet not loaded because of MIME-type but could not find the right solution.
This is how my webpack.config.js looks like:
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = (env = {}) => ({
entry: ['./src/main.scss', './src/main.jsx'],
output: {
path: path.resolve(__dirname, `./html/${env.branch || 'master'}`),
filename: 'kt-infoscreen.js',
library: 'ktInfoScreen',
libraryExport: 'default',
libraryTarget: 'umd',
},
mode: env.mode || 'development',
devtool: 'eval',
resolve: {
extensions: ['.js', '.jsx', '.css', '.sass', '.scss'],
},
plugins: [
new CopyWebpackPlugin([{
from: 'dev/static/',
to: 'static/'
},
'dev/index.html',
]),
],
module: {
rules: [{
enforce: 'pre',
test: [/\.js$/, /\.jsx$/],
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
failOnError: env === 'production',
},
},
{
test: [/\.js$/, /\.jsx$/],
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: [/\.css$/g, /\.sass$/g, /\.scss$/g],
use: [{
loader: 'css-hot-loader',
},
{
loader: 'file-loader',
options: {
name: 'kt-infoscreen.css',
},
},
{
loader: 'sass-loader',
options: {
includePaths: ['./node_modules'],
outputStyle: env === 'production' ? 'compressed' : 'nested',
},
},
],
},
],
},
watchOptions: {
poll: 1500,
},
devServer: {
contentBase: path.resolve(__dirname, './dev/'),
watchContentBase: true,
disableHostCheck: true,
host: '127.0.0.1',
port: 3999,
// public: process.env.webpack_public_address || null,
overlay: true,
},
});
Can someone help here ?
As I said, the created yarn build file completely works it's only the webpack-dev server that does not work.

Related

Webpack issues with css/scss on public folder load

I need help with my webpack.
Currently I have a simple structor but doesn't load the css into the public folder
instead loads 2 inline tags.
My Issue is:
the public folder as a index.html with two css with for some reason the get duplicated with my bundle.js.
How do I set a normal css in there?
Surely my webpack is wrong.
I'm using react and I have a sass folder with all scss files.
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: ["./src/index.js"],
mode: "development",
module: {
rules: [{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
sideEffects: true,
},
{
// Images
test: /\.(png|svg|jpg|gif)$/,
use: {
'loader': 'file-loader',
'options': {
'name': "[name].[ext]",
'outputPath': 'assets/images/'
}
}
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
},
},
},
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: {
presets: ["#babel/env"]
}
}
],
},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
output: {
path: path.resolve(__dirname, "public/"),
publicPath: "/public/",
filename: "bundle.js"
},
devServer: {
historyApiFallback: true,
contentBase: path.join(__dirname, "public/"),
port: 3000,
hot: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src", "pages/index.html")
})
]
};

Webpack 5 not showing images

I have a vue 3 app where I set up webpack 5 eventually. As I see I eliminated all my issues now the only thing remains is that it does not load my svg-s and images when I run the webpack serve script in dev mode. How can I configure webpack so that it would bundle my svg-s from the scr/assets folder?
my webpack config:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const env = process.env.NODE_ENV || 'development';
const mode = process.env.VUE_APP_MODE || 'not-fullstack';
module.exports = {
mode: 'development',
entry: './src/main.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
alias: {
vue: '#vue/runtime-dom',
'#': path.join(__dirname, 'src'),
},
fallback: { crypto: false, stream: false },
},
module: {
rules: [
{
test: /\.vue$/,
use: [
{
loader: 'vue-loader',
},
],
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader', 'postcss-loader'],
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'images/[name].[hash].[ext]',
},
type: 'asset/resource',
},
{
test: /\.svg$/i,
use: [
{
loader: 'url-loader',
options: {
encoding: false,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, './public/index.html'),
}),
new VueLoaderPlugin(),
new CopyPlugin([
{ noErrorOnMissing: true, from: './src/assets', to: 'images' },
]),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env),
'process.env.VUE_APP_MODE': JSON.stringify(mode),
}),
],
devServer: {
historyApiFallback: true,
compress: true,
port: 3000,
},
};
And I reference my svg-s in my Vue component like this:
<img src="../../assets/logo.svg" alt="logo" />
As you can see I tried with the copy-webpack-plugin, maybe I just configured it wrong.
Thank you for your help in advance!
The config in webpack5 changed a lot
{
loader: 'url-loader',
options: {
encoding: false,
},
This is not working anymore. The url-loader is even removed from the npm packages.
The current way is found in the documentation
https://webpack.js.org/guides/asset-management/#loading-images

Webpack Image for React Application

I've read through most posts, but still can't figure out why my application won't display an image. I'm using webpack 4+ in a React application.
My webpack config:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
entry: { main: './src/index.js' },
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.(html)$/,
use: ['html-loader'],
},
{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-env', '#babel/preset-react'],
},
},
{
test: /\.(s*)css$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'style.css',
})
],
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
devServer: {
historyApiFallback: true,
contentBase: './',
watchOptions: {
aggregateTimeout: 300,
poll: 1000,
},
},
};
I then call an image JSX tag in one of my components <img src={require('../assets/GGGlogo.png')} /> where the assets folder is also contained within my src folder. When I run the webpack dev server, everything compiles successfully and the app starts.
However, my chrome console outputs: GET http://localhost:8080/app/b561359832a3836146dd3f42233e77f7.png 404 (Not Found)
When I run my dev script to make a dist folder with the bundle.js and image, the above hash is indeed the image I want. Why is there a 404 error when trying to find the image?

My Vue build in webpack produces a huge (850kb) vendor file, how do I make it the expected 85kb?

Solved:
devtool: '#eval-source-map'
Includes a source map in the output
Original issue
As stated, the webpack build produces an enormous bundle/vendor file with Vue as my only import. I cannot see for the life of me how people get it down to 80kb.
As far as I can see, there is a vue-loader and the file gets minified, so why would it come out enormous?
var path = require('path') var webpack = require('webpack')
module.exports = { entry: './src/main.js', output: {
path: path.resolve(__dirname, './static'),
publicPath: '/static/',
filename: 'js/login-view.js' }, module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
useRelativePath: true,
publicPath: './static/images/'
}
}
] }, resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json'] }, devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true }, performance: {
hints: false }, devtool: '#eval-source-map' }
if (process.env.NODE_ENV === 'production') { // module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
// compress: true,
compress: {
warnings: false
},
mangle: true,
}),
new webpack.LoaderOptionsPlugin({
minimize: true
}) ]) }
devtool: '#eval-source-map'
was the culprit. It was getting included in all builds and it puts the sourcemap in the files. I removed this and dropped the file to ~90kb.

webpack dev server does not show the content

I have the following problem when running the webpack dev server:
when I run npm start, it show the following:
➜ directory git:(staging) ✗ npm start
directory #1.0.0 start directory
BUILD_DEV=1 BUILD_STAGING=1 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/
webpack result is served from /undefined/
content is served from
directory
404s will fallback to /index.html
Hash: 75773622412153d5f921
Version: webpack 1.12.11
Time: 43330ms
I guess the problem might because the following line:
webpack result is served from /undefined/
When I open the browser at http://localhost:8080/, it appear as follow:
Cannot GET /
and there is no thing in the console.
Do you have any ideas for this problem ?
UPDATE: WEBPACK CONFIG FILE
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const deps = [
'moment/min/moment.min.js',
'underscore/underscore-min.js',
];
/* Include SASS path here if you want to this in your sass files:
* #import 'bourbon';
*/
const bourbon = require('node-bourbon').includePaths;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const SASS_DEPS = [bourbon].toString();
const BUILD_NUMBER = process.env.CI_BUILD_NUMBER;
const common = {
entry: path.resolve(ROOT_PATH, 'app/index.js'),
output: {
filename: BUILD_NUMBER + '-[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: `/${BUILD_NUMBER}/`,
},
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass?includePaths[]=' + SASS_DEPS],
include: path.resolve(ROOT_PATH, 'app'),
},
{
test: /\.css$/,
loaders: [
'style',
'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'sass?includePaths[]=' + SASS_DEPS,
'postcss'
],
include: path.resolve(ROOT_PATH),
exclude: /(pure\/grids|Grids).*\.css$/,
},
{
test: /(pure\/grids|Grids).*\.css$/,
loaders: [
'style',
'css',
'sass?includePaths[]=' + SASS_DEPS,
],
include: path.resolve(ROOT_PATH),
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&minetype=application/font-woff',
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
},
{
test: /\.json$/,
loader: 'json',
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
template: path.resolve(ROOT_PATH, 'app/index.html'),
inject: 'body',
minify: {
removeComments: true,
collapseWhitespace: true,
},
}),
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')),
__STAGING__: JSON.stringify(JSON.parse(process.env.BUILD_STAGING || 'false')),
__API_HOST__: JSON.stringify(process.env.BUILD_STAGING ? 'my.api' : 'my.api'),
}),
],
resolve: {
alias: {
'styles': path.resolve(ROOT_PATH, 'app/styles'),
},
extensions: ['', '.js', '.jsx', '.json'],
},
postcss: function() {
return [
require('postcss-import'),
require('autoprefixer'),
require('postcss-cssnext'),
]
}
};
if (TARGET === 'start' || !TARGET) {
module.exports = merge(common, {
output: {
filename: '[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: '/',
},
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'react-hot',
'babel-loader'
],
include: path.resolve(ROOT_PATH, 'app'),
},
],
},
devServer: {
colors: true,
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
});
} else if (TARGET === 'build' || TARGET === 'builds') {
const config = {
resolve: {
alias: {},
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: path.resolve(ROOT_PATH, 'app'),
},
],
noParse: [],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
screw_ie8: true,
warnings: false,
},
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env': { 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
}),
],
};
deps.forEach((dep) => {
const depPath = path.resolve(nodeModulesDir, dep);
config.resolve.alias[dep.split(path.sep)[0]] = depPath;
config.module.noParse.push(depPath);
});
module.exports = merge(common, config);
}
Same problem occurred to me when i started using babel-loader > 6.
It was fixed by adding contentBase in webpack dev server configuration.
In my case it looked like this
new WebPackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
contentBase: __dirname + '/public'
}).listen(3000, 'localhost')
I would be great to see your webpack config file to pin point the exact problem, but from the error message, there could be multiple problem
Make sure you are on the right port
Make sure your webpack config has
path and public path setup
Make sure you have contentBase setup as
well
Without seeing your webpack file and more concrete detail, it is quite hard to pinpoint the issue. But you can always go to https://webpack.github.io/docs/webpack-dev-server.html for information on how to set it up.

Categories

Resources