Webpack config not accepting to config mode option - javascript

**getting error when trying to add mode option to the webpack config i need to configure {mode:'developement' } to enable hmp by looking at this answer github.com/webpack-contrib/webpack-hot-middleware/issues/… **
WebpackOptionsValidationError: Invalid configuration object. Webpack
has been initialised using a configuration object that does not match
the API schema.
- configuration has an unknown property 'mode'. These properties are valid:
object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?,
node?, output?, performance?, plugins?, profile?, recordsInputPath?,
recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?,
target?, watch?, watchOptions? }
For typos: please correct them.
For loader options: webpack 2 no longer allows custom properties in configuration.
Loaders should be updated to allow passing options via loader options in module.rules.
Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
plugins: [
new webpack.LoaderOptionsPlugin({
// test: /.xxx$/, // may apply this only for some modules
options: {
mode: ...
}
})
]
at webpack (C:\Users\asdf\WebstormProjects\node_modules\webpack\lib\webpack.js:19:9)
at Object. (
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:282:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
/* eslint-disable */
const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const commonConfig = require('./webpack.config.common');
module.exports = webpackMerge(
commonConfig,
{
devtool: 'cheap-module-eval-source-map',
entry: {
main: ['babel-polyfill', 'webpack-hot-middleware/client', './app/index.js'],
},
output: {
path: __dirname,
publicPath: '/',
filename: '[hash].bundle.js',
},
module: {
rules: [
{
test: /\.mspcss/,
use: [
'style-loader',
'css-loader?modules=true&importLoaders=1&localIdentName=[local]___[hash:base64:5]',
'resolve-url-loader',
'sass-loader?sourceMap'
]
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader?sourceMap']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development'),
BABEL_ENV: JSON.stringify('development'),
},
__DEV__: true,
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
title: 'some- Development',
template: path.resolve(__dirname, 'index.ejs'),
filename: path.resolve(__dirname, 'index.html'),
favicon: 'favicon.ico',
inject: 'body'
}),
]
}
)
/* eslint-enable */

What version of webpack are you using? You are probably on version 2 or 3 and the latest version of webpack-dev-server (3.2.1) targets webpack 4. I had the same issue and fixed it by installing webpack-dev-server version 2.11.5
npm uninstall webpack-dev-server
npm i -D webpack-dev-server#2.11.5

Related

Webpack generator https://createapp.dev/ fail starting the project

I have found this website which basically is generating a very nice webpack/babel boilerplate structure the problem is that I have some errors when I am trying to run the boilerplate that I do not understand:
> empty-project#1.0.0 start /Users/user.name/Desktop/empty-project
> webpack serve --hot --mode development
[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
- configuration.plugins[3] should be one of these:
object { apply, … } | function
-> Plugin of type object or instanceof Function.
Details:
* configuration.plugins[3] should be an object:
object { apply, … }
-> Plugin instance.
* configuration.plugins[3] should be an instance of function.
-> Function acting as plugin.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! empty-project#1.0.0 start: `webpack serve --hot --mode development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the empty-project#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
and this is webpack config file:
const webpack = require('webpack');
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const config = {
entry: [
'react-hot-loader/patch',
'./src/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
}
]
},
resolve: {
extensions: [
'.js',
'.jsx'
],
alias: {
'react-dom': '#hot-loader/react-dom'
}
},
devServer: {
contentBase: './dist'
},
plugins: [
new CopyPlugin({
patterns: [{ from: 'src/index.html' }],
}),
new HtmlWebpackPlugin({
templateContent: ({ htmlWebpackPlugin }) => '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>' + htmlWebpackPlugin.options.title + '</title></head><body><div id=\"app\"></div></body></html>',
filename: 'index.html',
}),,
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
}),
new MiniCssExtractPlugin(),
new CleanWebpackPlugin()
]
};
module.exports = config;
but you can also check the webpack generator, however I'm not sure why is not working :|
You have double commas after a HtmlWebpackPlugin. Just remove extra one of two ',' signs
should be:
}),
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
}),
new MiniCssExtractPlugin(),
new CleanWebpackPlugin()
]
};
module.exports = config;
currently:
}),,
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
}),
new MiniCssExtractPlugin(),
new CleanWebpackPlugin()
]
};
module.exports = config;

Getting 'ReferenceError: document is not defined' only when I run webpack --watch?

Why would document stop being defined only when I run webpack --watch? When I run my build or dev script, compiling works great. It's only when I try and watch. New to WP.
My end goal here is to polyfill my client-side JS and auto-reload the browser window that LiveServer opens (VSCode plugin). Right now, I'm just trying to automatically compile my code after making changes which will trigger LiveServer to reload. Is there a better approach to this?
index.js
const errors = document.querySelector('.errors');
webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const NodemonPlugin = require('nodemon-webpack-plugin');
const config = {
watch: true,
entry: {
rater_stater: "./src/index.js",
},
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
"postcss-loader",
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "style.css",
chunkFilename: "style-[id].css",
}),
new NodemonPlugin({
env: {
NODE_ENV: 'development',
},
})
],
};
module.exports = (env, argv) => {
if (argv.mode === "development") {
config.devtool = "source-map";
}
if (argv.mode === "production") {
config.module.rules.push({
test: /\.js?$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
],
exclude: /node_modules/,
});
}
return config;
};
package.json
"scripts": {
"build": "webpack --mode=production",
"dev": "webpack --mode=development",
"watch": "webpack --watch"
},
error
ReferenceError: document is not defined
at /Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180375
at /Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180732
at Object.<anonymous> (/Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180735)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
Edit:
I'm also getting this error when it does compile with webpack --mode=development. It's like my variables are all set to null? I'm so confused. Why would this happen? I've tried changing it from var to let to const and still get the same error.
Edit 2:
Ran a couple more tests. It's like everything related to document is broken.. but I can console.log document. I just can't use querySelector, etc.
All of these issues stopped when I wrapped my code with
document.addEventListener("DOMContentLoaded", function() {
...code
}
🤦

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

i am new to reactjs and i am trying to configure my first project with webpack.
webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://127.0.0.1:8080/',
'webpack/hot/only-dev-server',
'./src'
],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
resolve: {
modulesDirectories: ['node_modules', 'src'],
extensions: ['', '.js']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?presets[]=react,presets[]=es2015']
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
after creating a react project i am trying to run it using webpack-dev-server command. but i get a long list of error as shown below.
Invalid configuration object. Webpack has been initialised using a configuration
object that does not match the API schema.
- configuration.resolve has an unknown property 'modulesDirectories'.
These properties are valid: object { alias?, aliasFields?,cachePredicate?,
descriptionFiles?,enforceExtension?, enforceModuleExtension?,extensions?,
fileSystem?, mainFields?, mainFiles?,moduleExtensions?, modules?, plugins?,
resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }
- configuration.resolve.extensions[0] should not be empty.
my webpack version
webpack -version
3.0.0

Webpack config issue with loaders when running gulp serve or build

Am new to using webpack and used Fountain Web App to scaffold my setup and then adding in my own stuff. Am running into issues I am not sure what else to do with. I have searched and tried, but not sure if the issues are being caused by loaders or what.
When I run gulp serve or build, I get this:
C:\vapor\source\mgmtPortal\dashboard>gulp serve
[14:23:43] Loading C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\browsersync.js
[14:23:43] Loading C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\karma.js
[14:23:44] Loading C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\misc.js
[14:23:44] Loading C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\webpack.js
fallbackLoader option has been deprecated - replace with "fallback"
loader option has been deprecated - replace with "use"
[14:23:45] Using gulpfile C:\vapor\source\mgmtPortal\dashboard\gulpfile.js
[14:23:45] Starting 'serve'...
[14:23:45] Starting 'webpack:watch'...
[14:23:45] 'webpack:watch' errored after 121 ms
[14:23:45] WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration has an unknown property 'debug'. These properties are valid:
object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
The 'debug' property was removed in webpack 2.
Loaders should be updated to allow passing this option via loader options in module.rules.
Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:
plugins: [
new webpack.LoaderOptionsPlugin({
debug: true
})
]
at webpack (C:\vapor\source\mgmtPortal\dashboard\node_modules\webpack\lib\webpack.js:19:9)
at webpackWrapper (C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\webpack.js:24:26)
at gulp.task.done (C:\vapor\source\mgmtPortal\dashboard\gulp_tasks\webpack.js:15:3)
at taskWrapper (C:\vapor\source\mgmtPortal\dashboard\node_modules\undertaker\lib\set-task.js:13:15)
at taskWrapper (C:\vapor\source\mgmtPortal\dashboard\node_modules\undertaker\lib\set-task.js:13:15)
at taskWrapper (C:\vapor\source\mgmtPortal\dashboard\node_modules\undertaker\lib\set-task.js:13:15)
at bound (domain.js:280:14)
at runBound (domain.js:293:12)
at asyncRunner (C:\vapor\source\mgmtPortal\dashboard\node_modules\async-done\index.js:36:18)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
at Module.runMain (module.js:606:11)
at run (bootstrap_node.js:390:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:505:3
[14:23:45] 'serve' errored after 127 ms
My webpack config looks like this:
const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');
// const rules = {
// // ...
// componentStyles: {
// test: /\.scss$/,
// loaders: ["style-loader", "css-loader", "sass-loader"],
// exclude: path.resolve(__dirname, 'src/app')
// },
// fonts: {
// test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
// loader: 'file-loader?name=fonts/[name].[ext]'
// },
// // ...
// }
// const config = module.exports = {};
// config.module = {
// rules: [
// // ...
// rules.componentStyles,
// rules.fonts,
// // ...
// ]
// };
module.exports = {
module: {
// preLoaders: [{
// test: /\.js$/,
// exclude: /node_modules/,
// loader: 'eslint'
// }],
loaders: [{
test: /.json$/,
loaders: [
'json'
]
},
{
test: /\.(css|scss)$/,
loaders: [
'style',
'css',
'sass',
'postcss'
]
},
{
test: /.html$/,
loaders: [
'html'
]
}
]
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"Tether": "tether"
}),
new HtmlWebpackPlugin({
template: conf.path.src('index.html')
}),
new webpack.ProvidePlugin({ // inject ES5 modules as global vars
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Tether: 'tether'
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
conf.paths.src
)
],
postcss: () => [autoprefixer],
debug: true,
devtool: 'source-map',
output: {
path: path.join(process.cwd(), conf.paths.tmp),
filename: 'index.js'
},
entry: `./${conf.path.src('index')}`
};
Can any of you lend a hand with helping me on this?
Thanks much.
To resolve this specific error you need to remove debug: true, from your webpack config. The error is saying that the debug parameter is not valid for Webpack 2, and it was only valid in webpack 1.
The line of the error is here:
[14:23:45] WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration has an unknown property 'debug'. These properties are valid:
object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
The 'debug' property was removed in webpack 2.
It sounds like you upgraded to webpack 2, maybe unintentionally. If it was on purpose, you can view the migration guide here, on how to properly structure your configuration file. It likely needs more changed if you plan on staying with Webpack 2.
If it was unintentional, you can reinstall webpack by running the npm command, but it is not recommended and not supported anymore.
npm install --save webpack#1.15.0

Still getting 'Symbol' is undefined' error even after adding babel-polyfill in my webpack

https://babeljs.io/docs/usage/polyfill/#usage-in-browser
I did not understand the lines on the documentation page under:
Usage in Browser heading
can someone help me with what else is required:
Below are my code snippets:
I'm using storybook as a boilerplate:
webpack.config.js file:
entry: [
'babel-polyfill',
require.resolve('react-dev-utils/webpackHotDevClient'),
paths.appIndexJs
]
index.js file:
import 'babel-polyfill';
import React from 'react';
Is there some other files also where I need to add babel-polyfill related code.
require('babel-polyfill');
var path = require('path');
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
var getClientEnvironment = require('./env');
var paths = require('./paths');
var publicPath = '/';
var publicUrl = '';
var env = getClientEnvironment(publicUrl);
module.exports = {
devtool: 'cheap-module-source-map',
entry: ['babel-polyfill',
require.resolve('react-dev-utils/webpackHotDevClient'),
require.resolve('./polyfills'),
paths.appIndexJs
],
output: {
path: paths.appBuild,
pathinfo: true,
filename: 'static/js/bundle.js',
publicPath: publicPath
},
resolve: {
fallback: paths.nodePaths,
extensions: ['.js', '.json', '.jsx', ''],
alias: {
'react-native': 'react-native-web'
}
},
module: {
// First, run the linter.
// It's important to do this before Babel processes the JS.
preLoaders: [{
test: /\.(js|jsx)$/,
loader: 'eslint',
include: paths.appSrc,
}],
loaders: [{
exclude: [/\.html$/, /\.(js|jsx)$/, /\.css$/, /\.json$/],
loader: 'url',
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: 'babel',
query: {
cacheDirectory: true
}
}, {
test: /\.css$/,
loader: 'style!css?importLoaders=1!postcss'
}, {
test: /\.json$/,
loader: 'json'
}
]
},
// We use PostCSS for autoprefixing only.
postcss: function() {
return [
autoprefixer({
browsers: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
},
plugins: [
new InterpolateHtmlPlugin({
PUBLIC_URL: publicUrl
}),
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
new webpack.DefinePlugin(env),
new webpack.HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
new WatchMissingNodeModulesPlugin(paths.appNodeModules)
],
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
There are two ways to get this code into your browser.
1 - Include the babel-polyfill module in the webpack bundle
2 - Load it as an external script in your html
Webpack - adding bundle dependencies with entry arrays
Put an array as the entry point to make the babel-polyfill module available to your bundle as an export.
With webpack.config.js, add babel-polyfill to your entry array.
The webpack docs explain how an entry array is handled:
What happens when you pass an array to entry? Passing an array of file
paths to the entry property creates what is known as a "multi-main
entry". This is useful when you would like to inject multiple
dependent files together and graph their dependencies into one
"chunk".
Webpack.config.js
require("babel-polyfill");
var config = {
devtool: 'cheap-module-eval-source-map',
entry: {
main: [
// configuration for babel6
['babel-polyfill', './src/js/main.js']
]
},
}
Alternative to Webpack - load babel-polyfill as an external script in the browser html
The alternative to using webpack would mean including the module as an external script in your html. It will then be available to code in the browser but the webpack bundle won't be directly aware of it.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.22.0/polyfill.js"></script>

Categories