I am pretty new to webpack and am confused by a range of answers. I have 3 components app.js, customButton, Sample.js whenever I change any text in any of the files the whole page is reloading. Can anyone help me out with webpack5 configuration if I have made any mistake.
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, "./dist"),
clean: true,
publicPath: "/static/",
sourceMapFilename: "[name].bundle.js.map"
},
devServer: {
contentBase: path.resolve(__dirname, "./dist"),
overlay: {
errors: true,
warnings: true
},
inline: true,
index: "index.html",
port: 8080,
writeToDisk: true,
stats: {
chunks: false,
modules: false,
publicPath: false,
assets: false,
children: false,
colors: true
},
},
optimization: {
splitChunks: {
chunks: "all"
}
},
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/,
type: 'asset/resource'
},
{
test: /\.css$/,
use: [
'style-loader', 'css-loader'
]
},
{
test: /\.s[ac]ss$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'react-hot-loader/webpack',
},
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react'],
plugins: ['#babel/plugin-proposal-class-properties']
}
}
]
},
// {
// test: /\.js$/,
// exclude: /node_modules/,
// use: [
// {
// loader: 'babel-loader',
// options: {
// presets: ['#babel/env'],
// plugins: ['#babel/plugin-proposal-class-properties']
// }
// }
// ]
// }
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "public", "index.html"),
}),
],
devtool: 'inline-source-map'
}`
My package.json scripts.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production --config webpack.prod.config.js",
"dev": "webpack serve --mode development --config webpack.dev.config.js --hot"
},
App.js
const App = () => {
return (
<div className="App">
<h2>Hi, Guyss !</h2>
<Suspense fallback={<div>Loading .. </div>}>
<CustomButton />
<Login />
</Suspense>
</div>
)
}
export default App;
Related
I've installed file-loader and url-loader, and added the below to my webpack config
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader',
options: {}
}]
},
{
test: /\.(png|jpg|gif)$/,
use: {
loader: 'url-loader',
},
},
below is my html
<img src="../src/assets/laughing.svg">
console error after npm run dev
Failed to load resource: the server responded with a status of 404 (Not Found)
I'm new to webpack, not sure what I'm doing wrong here....
Full config:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: {
bundle: path.resolve(__dirname, 'src/index.js'),
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name][contenthash].js',
clean: true,
assetModuleFilename: '[name][ext]',
},
devtool: 'source-map',
devServer: {
static: {
directory: path.resolve(__dirname, 'dist'),
},
port: 3000,
open: true,
hot: true,
compress: true,
historyApiFallback: true,
},
module: {
rules: [
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
},
},
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader',
options: {}
}]
},
{
test: /\.(png|jpg|gif)$/,
use: {
loader: 'url-loader',
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'Webpack App',
filename: 'index.html',
template: 'src/index.html',
}),
new HtmlWebpackPlugin({
title: 'Webpack App',
filename: 'about.html',
template: 'src/about.html',
}),
],
}
Any idea how to fix this?
Image works when I'm not not running npm run dev. So img src must be correct.
I think you should remove file-loader and url-loader
Here's the documentation example:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource', // EXAMPLE HERE
},
],
},
};
only use the asset/resource module
I'm trying to integrate PWA in my react project, when i run using webpack-dev-server i can see the PWA app that i can install in my computer, but when i build the project with webpack and try to run it, i can't do it anymore
webpack.config.js
const path = require("path");
const webpack = require("webpack");
const { styles } = require("#ckeditor/ckeditor5-dev-utils");
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const BUILD_DIR = path.resolve(__dirname, "public");
const APP_DIR = path.resolve(__dirname, "src");
const envs = require('./config/envs').getEnv;
const plugins = require('./webpack-plugins');
module.exports = (env) => {
console.log("OUTPUT: env", env)
const config = envs(env.NODE_ENV);
const mode = env.production ? 'production' : 'development';
return {
mode,
entry: `${APP_DIR}/index.js`,
output: {
filename: "js/bundle.js",
path: BUILD_DIR,
publicPath: "/"
},
node: {
net: "empty",
tls: "empty",
dns: "empty",
fs: "empty"
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
exclude: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css/
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
"babel-loader",
{
loader: "eslint-loader",
options: {
failOnError: true,
emitError: true,
emitWarning: true
}
}
]
},
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: "graphql-tag/loader"
},
{
test: /\.(jpg|png|gif|svg|pdf|ico)$/,
use: [
{
loader: "file-loader",
options: {
name: "[path][name]-[hash:8].[ext]"
}
}
],
exclude: [
/\.(js|jsx|mjs)$/,
/\.html$/,
/\.json$/,
/ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
/ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css/
]
},
{
test: /ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
use: ["raw-loader"]
},
{
test: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css/,
use: [
{
loader: "style-loader",
options: {
singleton: true
}
},
{
loader: "postcss-loader",
options: styles.getPostCssConfig({
themeImporter: {
themePath: require.resolve("#ckeditor/ckeditor5-theme-lark")
},
minify: true
})
}
]
}
]
},
devServer: {
historyApiFallback: true,
watchContentBase: true,
contentBase: "./public"
},
resolve: {
extensions: [".js"],
alias: {
src: path.resolve(__dirname, "src"),
shared: path.resolve(__dirname, "src", "shared"),
config: path.resolve(__dirname, "config"),
screens: path.resolve(__dirname, "src", "screens"),
package: path.resolve(__dirname, "package.json")
}
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new MomentLocalesPlugin({
localesToKeep: ['es-us', 'fr', 'es'],
}),
new webpack.DefinePlugin({
CONFIG: JSON.stringify(config),
}),
plugins.manifest,
plugins.sw
]
}
};
the Scripts on package.json
"build:local": "webpack --env.NODE_ENV=local --env.production --progress",
"start": "node server.js",
"dev": "webpack-dev-server --inline --watch --host 0.0.0.0 --env.NODE_ENV=local --env.development --progress"
Webpack packages used :
"webpack": "4.19.1",
"webpack-cli": "^2.0.15",
"webpack-dev-server": "^3.1.3",
"webpack-manifest-plugin": "^2.2.0"
PS: I tried both --env.production and --env.development in the build but neither worked
Any lead would be appreciated !
Making the app HTTPS fixed it, many thanks #Mathias
Hello Guys I have a simple question I'm using webpack 4 to build a simple application
I'm trying to change the NODE_ENV variable automatically by using the dotenv package
I use many tricks to do this but nothing works.
please some help thank you...
this is my all config file please help guys thank you
webpack.config.js
"use strict";
// Libraries
const path = require('path')
const webpack = require('webpack')
require('dotenv').config()
// Plugin(s)
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const TerserJSPlugin = require('terser-webpack-plugin')
// Configuration
const isDevMode = process.env.NODE_ENV !== 'production'
module.exports = {
mode: process.env.NODE_ENV,
context: path.resolve(__dirname, '../src'),
entry: {
app: [
'../src/resources/assets/js/app.js',
'../src/resources/assets/sass/app.scss'
]
},
output: {
path: path.resolve(process.cwd(), 'public/dist/.vuxt'),
filename: 'assets/js/[name].bundle.js',
chunkFilename: 'assets/js/[id].bundle.js'
},
devtool: 'source-map',
devServer: {
contentBase: path.resolve(__dirname, '../public'),
watchContentBase: true,
compress: true,
host: process.env.APP_HOST,
port: process.env.APP_PORT
},
resolve: {
modules: [
'node_modules',
path.resolve(__dirname, '../src')
],
extensions: ['.*', 'json', '.js', '.jsx', '.ts', '.tsx', '.css', '.scss'],
alias: {}
},
module: {
rules: [
{
test: [/.js$|.jsx$|.ts$|.tsx$/],
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
cwd: __dirname,
presets: ['#babel/preset-env', '#babel/typescript']
}
}
},
{
test: /\.html$/,
use: ['ejs-loader', 'extract-loader', 'html-loader']
},
{
test: [/.css$|.scss$/],
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: process.env.NODE_ENV === 'development',
reloadAll: true
}
},
{
loader: 'css-loader',
options: { sourceMap: true }
},
{
loader: 'postcss-loader',
options: { sourceMap: true }
},
{
loader: 'sass-loader',
options: { sourceMap: true }
}
]
},
{
test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
outputPath: 'assets/images/'
}
}
]
},
{
test: /\.((woff2?|svg)(\?v=[0-9]\.[0-9]\.[0-9]))|(woff2?|svg|jpe?g|png|gif|ico)$/,
use: ['url-loader?limit=10000']
}
]
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: true
},
sourceMap: true
}),
new TerserJSPlugin({
terserOptions: {
ecma: undefined,
warnings: false,
parse: {},
compress: {},
mangle: true,
module: false,
output: null,
toplevel: false,
nameCache: null,
ie8: false,
keep_classnames: undefined,
keep_fnames: false,
safari10: false,
}
}),
new OptimizeCSSAssetsPlugin({
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
}
})
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
hash: true,
inject: true,
minify: {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
},
title: process.env.APP_NAME,
meta: {
viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no',
'theme-color': '#0000'
},
favicon: '../src/resources/assets/images/favicon.png',
template: path.resolve(__dirname, '../src/resources/views/index.html')
}),
new MiniCssExtractPlugin({
filename: isDevMode ? 'assets/css/[name].css' : 'assets/css/[name].[hash].css',
chunkFilename: isDevMode ? 'assets/css/[id].css' : 'assets/css/[id].[hash].css',
})
]
};
.env
NODE_ENV=production
app.js
console.log('You are in ', process.env.NODE_ENV, 'Mode')
package.json
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node node_modules/webpack/bin/webpack.js --progress --hide-modules --config webpack/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production webpack -p --no-progress --hide-modules --config webpack/webpack.config.js",
"serve": "npm run start",
"start": "cross-env NODE_ENV=development node node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --open --config webpack/webpack.config.js"
}
you can try passing env value via command line while starting the app.
example: npm start env=production
I have one .html page(index.html) and one entry point(index.js) and I want that dist folder keeps folder structure of my source files.
./webpack.config.js
./src/index/index.html
./src/index/index.js
./src/index/script1.js
./src/index/style1.scss
./src/assets/imgs/bg.jpg
I manage to write a webpack config file that works as I want but only when I use 'npm run build' and webpack give me a final build version.'
if I use 'npm run dev' then dev server opens a page that shows directories list.
How can I solve my problem?
this is my webpack.config.js
const webpack = require("webpack");
const path = require("path");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
optimization: {
minimize: false
},
entry: {'index': './src/index/index.js'},
output: {
filename: '[name]/[name].js',
path: path.resolve(__dirname, './dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: process.env.NODE_ENV === 'development',
reloadAll: true,
},
},
'css-loader',
'postcss-loader'
]
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: process.env.NODE_ENV === 'development',
reloadAll: true,
},
},
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.html$/,
exclude: /node_modules/,
use: [
{
loader: 'html-loader',
options: {
minimize: false,
publicPath: './'
}
}
]
},
{
test: /\.(png|jpg|jpeg)$/,
exclude: /node_modules/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/imgs/',
publicPath: '../assets/imgs/'
}
}
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name]/[name].css",
chunkFilename: '[id].css',
ignoreOrder: false
}),
new HtmlWebpackPlugin({
filename: 'index/index.html',
inject: true,
chunks: ['index'],
template: './src/index/index.html'
}),
new CleanWebpackPlugin()
]
};
package.json :
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
}
I want dist folder to be like this :
./dist/index/index.html
./dist/index/index.js --> final .js bundle
./dist/index/index.css --> final .css bundle
./dist/assets/imgs/bg.jpg
I can't get webpack-dev-server working with eslint.
Here is my wepback config:
const path = require('path');
const PATHS = {
app: path.join(__dirname, 'app/js/app.js'),
build: path.join(__dirname, 'build')
};
module.exports = {
entry: {
app: PATHS.app
},
output: {
path: PATHS.build,
filename: 'bundle.js'
},
devServer: {
contentBase: 'dist'
},
module: {
loaders: [
{
test: /\.(jsx|js)?$/,
exclude: /node_modules/,
loader: ['babel']
},
{
test: /\.js$/, loader: "eslint-loader", exclude: /node_modules/
},
{
test: /\.json$/, loader: "json-loader", exclude: /node_modules/
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
loader: "url-loader?limit=10000"
}
]
},
resolve: {
extensions: ['', 'jsx', '.js', '.es6', '.css']
}
};
And here is the npm scripts:
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --content-base build eslint",
"eslint": "eslint ./app"
},
Do I need something else even though I have the .eslintrc.json file and it's from a different project I was working and it works there but using custom node server.
Thanks