when i try to run my webpack-dev-server, it gives me following error, that module is not found - webpack-dev-server

[![const path = require("path");
const webpack = require("webpack");
module.exports = {
mode: "development",
entry: "./src/app.js",
output: {
path: path.resolve(__dirname, "assets", "scripts"),
filename: "app.js",
publicPath: "./src",
},
devServer: {
hot: true,
host: "0.0.0.0",
port: 4000,
open: true,
},
module: {
rules: [{
test: /.css$/,
use: ["style-loader", "css-loader"],
}, ],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
//..
}),
],
};]1]1

i have change my command "webpack-dev-server" to "webpack serve" in my package.json file and my code is now working..

Related

Window is not defined after a build with Webpack

I am developing a reactJS application and also I am using WebPack 4.29.6 the problem that I face here it is that locally it works everything perfect when I run the npm run dev command while when I want to deploy in server I don't know how to do it I am building the app with the build:production command then it generates /dist folder inside with all files now here I try to run bundle.js it gives me this error: ReferenceError: window is not defined.
these are command's that i use to start my app:
"scripts": {
"dev": "cross-env webpack-dev-server --config ./webpack.config.dev.js --mode development",
"build:production": "cross-env webpack --config webpack.config.production.js --mode production"
}
this is my webpack.config.common.js
const path = require('path');
const webpack = require('webpack');
const outputPath = path.join(__dirname, '/dist');
const port = process.env.PORT || 4000;
module.exports = {
context: __dirname,
entry: './src/index.jsx',
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: outputPath,
publicPath: '/',
filename: 'bundle.js',
sourceMapFilename: 'bundle.map',
},
devServer: {
port,
historyApiFallback: true,
compress: true,
contentBase: './dist',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader'],
},
{
test: /\.less$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'less-loader',
},
],
},
{
test: /\.css$/,
use: ['css-loader'],
},
{
test: /\.svg$/,
loader: 'svg-inline-loader',
},
{
test: /\.(png|jpg|gif|woff(2)?|ttf|eot|svg)$/,
exclude: [
/\.(js|jsx|mjs)$/,
/\.html$/,
/\.json$/,
/\.(less|config|variables|overrides)$/,
],
use: [
{
loader: 'file-loader',
},
],
},
],
},
plugins: [
new webpack.ProvidePlugin({
Promise: 'es6-promise-promise',
}),
],
};
this is my webpack.config.dev.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackCommonConfig = require('./webpack.config.common');
module.exports = merge(webpackCommonConfig, {
mode: 'development',
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, '/index.html'),
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
],
devtool: 'inline-source-map',
devServer: {
hot: true,
open: true,
},
externals: {
// global app config object
config: JSON.stringify({
apiUrl: 'http://localhost:3000',
}),
},
});
this is my webpack.config.production.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpackCommonConfig = require('./webpack.config.common');
module.exports = merge(webpackCommonConfig, {
mode: 'production',
plugins: [new webpack.EnvironmentPlugin({ NODE_ENV: 'production' })],
optimization: {
minimizer: [
// we specify a custom UglifyJsPlugin here to get source maps in production
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: true,
},
sourceMap: true,
}),
],
},
devtool: 'source-map',
devServer: {
compress: true,
},
});
It may be late to answer but it may help someone else. I also had the ReferenceError: window is not defined. issue with Webpack 4, and found that adding globalObject: 'this' line to the output section in webpack config file fixed my problem:
output: {
globalObject: "this",
filename: "[name].js",
path: path.join(__dirname, "build/package"),
publicPath: "/resources/",
}
You can see the issue was discussed here
and the Webpack documentation about the globalObject setting here.
Using global worked for me.
const window = global.window
if (window && window.localStorage) {
const storageLogLevel = window.localStorage.getItem(LOG_LEVEL_KEY)
switch (storageLogLevel) {
case LogLevel.DEBUG:
logLevel = 0
break
case LogLevel.INFO:
logLevel = 1
break
case LogLevel.WARNING:
logLevel = 2
break
case LogLevel.CRITICAL:
logLevel = 3
break
default:
logLevel = 1
}
}

webpack-dev-server exits with status code 1

I have three files webpack.config.base, webpack.config.dev, webpack.config.prod with respective code:
** webpack.config.base**
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const parentDir = path.join(__dirname, '../');
module.exports = {
entry: [
path.join(parentDir, 'index.js'),
],
resolve: {
extensions: ['.js', '.jsx', '.json'],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
use: [
{
loader: 'image-webpack-loader',
options: {
bypassOnDebug: true,
},
},
'url-loader?limit=10000',
],
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader'],
}),
},
],
},
output: {
path: `${parentDir}/dist`,
filename: 'bundle.js',
},
plugins: [
new ExtractTextPlugin({
filename: 'main.css',
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
};
** webpack.config.dev**
const webpack = require('webpack');
const merge = require('webpack-merge');
const path = require('path');
const parentDir = path.join(__dirname, '../');
const config = require('./webpack.config.base.js');
module.exports = merge(config, {
devServer: {
inline: true,
colors: true,
progress: true,
hot: true,
open: true,
bail: true,
quiet: true,
contentBase: parentDir,
port: 7070,
historyApiFallback: true,
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
});
Production:
const webpack = require('webpack');
const config = require('./webpack.config.base.js');
config.plugins = config.plugins.concat([
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
]);
module.exports = config;
Script in package.json is
"dev": "./node_modules/.bin/webpack-dev-server --mode development --config ./webpack/webpack.config.dev.js",
On using npm run dev webpack dev server exits with status code-1. can anybody please tell where I'm getting wrong? Versions I am using is:
"webpack": "^4.6.0",
"webpack-cli": "^2.1.2",
"webpack-dev-server": "^3.1.4"
Thanks in advance. I have tried using this same in single file and it runs well, but when divided like this in three different files that time it creates this error. All these files are in webpack folder at root directory.
These three options were creating an issue:
bail: true,
quiet: true,
colors: true
I removed and now working fine. If anybody can update why it was so will be great for further understanding.

Enable source maps in Webpack

I have a problems with souce maps. They are generated but apparently not used.
I use webpack-dev-server, react hot module replacement and Webpack v3.x if that is important.
Inside of my webpack-config i use devtool: 'source-map' and I run my script like this:
"webpack": "cross-env NODE_ENV=development webpack-dev-server -d --config webpack.config.js"
Example of error that I get
When I click on this client?e36c:157 it doesn't take me to source code but:
If I remove devtools from webpack.config and -d tag from script I get the same output
**webpack.config.js**
const path = require('path')
const webpack = require('webpack')
const publicPath = path.resolve(__dirname, './src/client')
const buildPath = path.resolve(__dirname, './src')
// const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
const Write = require('write-file-webpack-plugin')
process.noDeprecation = true
module.exports = {
devtool: 'source-map',
performance: {
hints: false,
},
devServer: {
hot: true,
port: 3001,
host: 'localhost',
/* Needed only if using Browsersync */
headers: { 'Access-Control-Allow-Origin': '*', },
proxy: {
'**': {
target: 'http://localhost:3000',
secure: false,
changeOrigin: true,
},
},
},
context: publicPath,
entry: {
bundle: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3001',
'webpack/hot/only-dev-server',
'script-loader!jquery/dist/jquery.min.js',
'script-loader!tether/dist/js/tether.min.js',
'script-loader!bootstrap/dist/js/bootstrap.min.js',
'./app.js',
],
},
output: {
path: path.join(buildPath, 'dist'),
filename: '[name].js',
publicPath: 'http://localhost:3001/',
},
resolve: {
extensions: [ '.js', '.jsx', ],
alias: {
// Container
Container: path.resolve(__dirname, 'src/client/scenes/Container.jsx'),
// Components
FormComponent: path.resolve(
__dirname,
'src/client/scenes/feature/components/FormComponent.jsx'
),
Feature: path.resolve(__dirname, 'src/client/scenes/feature/Feature.jsx'),
TitleComponent: path.resolve(
__dirname,
'src/client/scenes/home/components/TitleComponent.jsx'
),
Home: path.resolve(__dirname, 'src/client/scenes/home/Home.jsx'),
Navigation: path.resolve(__dirname, 'src/client/scenes/shared/navigation/Navigation.jsx'),
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules|dist|build/,
loader: 'babel-loader',
options: {
babelrc: true,
},
},
{
test: /\.local\.(css|scss)$/,
use: [
'style-loader',
'css-loader?sourceMap&modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
'postcss-loader?sourceMap',
'sass-loader?sourceMap',
{
loader: 'sass-resources-loader',
options: {
resources: [
path.resolve(__dirname, './src/client/styles/scss/variables.scss'),
],
},
},
],
},
{
test: /^((?!\.local).)+\.(css|scss)$/,
use: [
'style-loader',
'css-loader?sourceMap',
'postcss-loader?sourceMap',
'sass-loader?sourceMap',
],
},
{
test: /\.(gif|png|jpg)$/,
/* We can specify custom publicPath if needed */
loader: 'url-loader',
},
],
},
plugins: [
new Write(),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery',
}),
],
}

extract-text-webpack-plugin error on production file

i have a problem with extract-text-webpack-plugin when i execute webpack to production. the error is this:
sh-3.2# yarn build
yarn build v0.24.5
$ webpack --config webpack.config.prod.js -p --watch --progress
10% building modules 1/1 modules 0 active
Webpack is watching the files…
78% advanced chunk optimization/Users/bcgarcia/Documents/tutoriales/redux/node_modules/extract-text-webpack-plugin/dist/index.js:188
chunk.sortModules();
^
TypeError: chunk.sortModules is not a function
at /Users/bcgarcia/Documents/tutoriales/redux/node_modules/extract-text-webpack-plugin/dist/index.js:188:19
at /Users/bcgarcia/Documents/tutoriales/redux/node_modules/extract-text-webpack-plugin/node_modules/async/dist/async.js:3083:16
at eachOfArrayLike (/Users/bcgarcia/Documents/tutoriales/redux/node_modules/extract-text-webpack-plugin/node_modules/async/dist/async.js:1003:9)
at eachOf (/Users/bcgarcia/Documents/tutoriales/redux/node_modules/extract-text-webpack-plugin/node_modules/async/dist/async.js:1051:5)
at Object.eachLimit (/Users/bcgarcia/Documents/tutoriales/redux/node_modules/extract-text-webpack-plugin/node_modules/async/dist/async.js:3145:5)
at Compilation.<anonymous> (/Users/bcgarcia/Documents/tutoriales/redux/node_modules/extract-text-webpack-plugin/dist/index.js:184:27)
at Compilation.applyPluginsAsyncSeries (/Users/bcgarcia/Documents/tutoriales/redux/node_modules/tapable/lib/Tapable.js:142:13)
at Compilation.seal (/Users/bcgarcia/Documents/tutoriales/redux/node_modules/webpack/lib/Compilation.js:570:8)
at /Users/bcgarcia/Documents/tutoriales/redux/node_modules/webpack/lib/Compiler.js:474:16
at /Users/bcgarcia/Documents/tutoriales/redux/node_modules/tapable/lib/Tapable.js:225:11
at _addModuleChain (/Users/bcgarcia/Documents/tutoriales/redux/node_modules/webpack/lib/Compilation.js:472:11)
at processModuleDependencies.err (/Users/bcgarcia/Documents/tutoriales/redux/node_modules/webpack/lib/Compilation.js:443:13)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
error Command failed with exit code 1.
here is my webpack.config file to production:
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const extractTextWebpackPlugin = require('extract-text-webpack-plugin')
module.exports = {
resolve: {
extensions: ['.js', '.jsx'],
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
},
entry: [
path.join(__dirname, 'src', 'index.jsx')
],
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: { loader: 'babel-loader'}
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
]
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: 'file-loader'
},
{
test: /\.(woff|woff2)$/,
use: 'url-loader?prefix=font/&limit=5000'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: 'url-loader?limit=10000&mimetype=image/svg+xml'
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV) || 'development' }
}),
new webpack.optimize.OccurrenceOrderPlugin(true),
new extractTextWebpackPlugin(path.join(__dirname, 'build', 'styles.css')),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
title: "redux tuto",
template: path.join(__dirname, 'src', 'index.html'),
filename: 'index.html'
}),
new webpack.optimize.UglifyJsPlugin({
compress: { warning: false },
mangle: { except: ['$super', 'exports', 'require'] }
}),
],
target: 'web',
devServer: {
host: '0.0.0.0',
hot: false,
port: 8081,
inline: true,
contentBase: path.join(__dirname, './build'),
historyApiFallback: true,
}
}
and the versions of packages are the next:
"extract-text-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^2.28.0",
"style-loader": "^0.18.2",
"webpack": "2.2.1",
"webpack-dev-server": "2.4.0"
anyone knows wich is the problem ? i have updated node and the error persist.
thanks in advance.

Browser downloads the HTML contents instead of showing it with webpack-dev-server

When I use webpack-dev-server with historyApiFallback replacing its index with index.php instead of index.html, A browser specifically Chrome will download its HTML contents instead of showing it.
How can I fix this issue?
My webpack.config.js is below.
webpack.config.js
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// const StyleLintPlugin = require('stylelint-webpack-plugin');
const fs = require('fs');
const entries = [
'./src/index.js',
];
module.exports = {
stats: {
assets: false,
colors: true,
version: false,
hash: true,
timings: true,
chunks: true,
chunkModules: true,
},
entry: entries,
output: {
path: path.resolve(__dirname, 'dist', 'assets'),
filename: '[name].js',
},
devtool: 'source-map',
devServer: {
port: 8000,
host: 'foobar.example.dev',
historyApiFallback: {
index: 'index.php',
},
noInfo: false,
stats: 'minimal',
contentBase: 'src',
hot: true,
inline: true,
https: true,
open: false,
cert: fs.readFileSync(path.resolve(__dirname, '..', 'shared', 'certs', 'foobar.example.dev.crt')),
key: fs.readFileSync(path.resolve(__dirname, '..', 'shared', 'certs', 'foobar.example.dev.key')),
proxy: {
'/wp-json/*': {
target: 'https://foobar.example.dev/wp-json',
port: 443,
secure: false,
changeOrigin: true,
},
},
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js?$/,
loader: 'eslint-loader',
options: {
configFile: '.eslintrc',
},
exclude: /(node_modules)/,
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
'postcss-loader',
'sass-loader',
],
}),
},
{
test: /\.(js|jsx)$/,
loaders: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'stage-1', 'react', 'react-hmre'],
},
},
// Images
// First use Base64 Encoded images if it is smaller than 10kb
// Otherwise use hashed images and optimize the image
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'url-loader?limit=10000&name=images/[name].[hash].[ext]',
],
},
// Fonts
{
test: /\.(eot|ttf|woff|woff2)$/,
loader: 'file-loader?name=fonts/[name].[ext]',
},
],
},
resolve: {
extensions: ['.js', '.scss', '.css'],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new StyleLintPlugin({
configFile: '.stylelintrc',
context: './src/styles',
files: '**/*.scss',
}),
new webpack.ProvidePlugin({
"React": "react",
}),
new ExtractTextPlugin({
filename: '/assets/main.css',
disable: process.env.NODE_ENV !== 'production',
allChunks: true,
}),
],
};
Here is the result of curl command
curl -I https://foobar.example.dev --insecure
HTTP/2 200
x-powered-by: Express
content-type: text/html; charset=utf-8
content-length: 9577

Resources