Webpack2 throws error when running webpack-dev-server - javascript

I have the following webpack config file:
var webpack = require('webpack');
var config = {
context: __dirname + '/src', // `__dirname` is root of project and `src` is source
entry: {
app: './app.js',
},
output: {
path: __dirname + '/dist', // `dist` is the destination
filename: '[name].bundle.js',
},
devServer: {
open: true, // to open the local server in browser
contentBase: __dirname + '/src'
},
module: {
rules: [
{
test: /\.js$/, //Check for all js files
use: [{
loader: 'babel-loader',
options: { presets: ['es2015'] }
}]
}
]
}
};
module.exports = config;
when I run "webpack-dev-server" I get the following error:
ERROR in (webpack)-dev-server/client?http://localhost:8080
Module build failed: Error: Couldn't find preset "es2015" relative to directory "/usr/local/lib/node_modules/webpack-dev-server/client/index.js?http:/"

Faced the same problem following a tutorial on Udemy. Adding the .babelrc worked for me.

Related

gulp-webpack error: Entry module not found: Error: cannot resolve module

When I try gulp scipts, it throws me the following error
ERROR in Entry module not found:
Error: Can't resolve 'C:/Users/milan/Local
Sites/project-university/app/public/wp-content/themes/fictional-university-theme/js/scripts.js'
in 'C:\Users\milan\Local Sites\project-university\app\public'
below is my webpack.config.js
const path = require('path'),
settings = require('./settings');
module.exports = {
entry: {
App: settings.themeLocation + "js/scripts.js"
},
output: {
path: path.resolve(__dirname, settings.themeLocation + "js"),
filename: "scripts-bundled.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
mode: 'development'
}
and my settings.js :
exports.urlToPreview = 'http://project-university.local/';
exports.themeLocation =
'C:/Users/milan/Local Sites/project-university/app/public/wp-content/themes/fictional-university-theme/';
Below is my file directory,
Project---- app------ public----------(wordpress content files)
The problem is the compiling path defined in settings.js. Change the defined path from
exports.themeLocation = './public/wp-content/themes/fictional-university-theme/';
to
exports.themeLocation = './wp-content/themes/fictional-university-theme/';

Getting Error: Module parse failed: ... unexpected character '#'

I am using webpack for the first time and want to use some css with my react/redux application. I followed a guide, but still seem to be having problems. I am getting the above error as you can see.
folder structure looks like this:
.git
-node_modules
-public
-bundle.js
-index.html
-src
-actions
-components
-reducers
app.js
-style
-style.css
.babelrc
.gitingore
package-lock.json
package.json
README.md
server.js
webpack.config.js
This is the exact error:
Uncaught Error: Module parse failed: C:\Users\Amazo\projects\reduxApp\style\style.css Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #row1 {
| margin-top: 15px;
| }
I will post my webpack config file below:
var path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public')
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude:/node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
resolve: {
extensions: ['.js','.jsx']
},
plugins: [
new HTMLWebpackPlugin({
template: 'public/index.html';
}),
new ExtractTextPlugin('style.css')
]
};
Add .css to your resolve
resolve: {
extensions: ['.js','.jsx', '.css']
},
Otherwise, webpack won't be able to process it correctly

gulp & webpack: ERROR in Entry module not found

I use webpack for working with JavaScript (ES6 modules bundling, converting to ES5, etc.) and gulp - for other tasks (jade, sass, etc.). I want to keep the webpack configuration in webpack.config.js, but to execute webpack by gulp task.
Project structure
📁 development 
  📁 es6 - source JS
   📄 main.js
  📁 js - output JS for development
   📄 index.js
📁 production
📄 webpack.config.js
📄 gulpfile.js
gulpfile.js
var gulp = require('gulp'),
//...
gulpwebpack = require('gulp-webpack')
gulp.task('gulpwebpack', function(){
return gulp.src('development/03_es6/main.js')
.pipe(gulpwebpack(require('./webpack.config.js')))
.pipe(gulp.dest('development/js/'));
});
// ...
gulp.task('watch', ['browser-sync', 'jade', 'sass'], function() {
// ...
gulp.watch('development/03_es6/*.js', ['test']);
});
gulp.task('default', ['watch']);
webpack.config.js
const NODE_ENV = process.env.NODE_ENV || 'development';
module.exports = {
context: __dirname + '/development',
entry: './03_es6/main.js',
output: {
path: __dirname + '/development/js/',
filename: 'index.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
}
//watch: NODE_ENV === 'development'
};
Problem
If just to execute webpack from the console (it means to execute the webpack independently from gulp), everything will be correct. However, if to execute gulp gulpwebpack, the error message will appear:
ERROR in Entry module not found: Error: Cannot resolve 'file' or 'directory' ./development/03_es6/main.js in C:\...\projectFrolder/development
I understand that the origin of error is here:
// ...
context: __dirname + '/development',
entry: './03_es6/main.js',
output: {
// ...
However development/03_es6/main.js and ./development/03_es6/main.js will not work too. Gulp can not read webpack.config.js correctly, isn't it?
I think, you should switch to
'use strict';
const gulp = require('gulp'),
named = require('vinyl-named'),
webpack = require('webpack-stream');
gulp.task('webpack', function () {
gulp.src('development/03_es6/main.js')
.pipe(named())
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'))
});
Remove entry from webpack.config.js:
module.exports = {
context: __dirname + '/development',
output: {
path: __dirname + '/development/js/',
filename: 'index.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
}
};

webpack output filename config error

When I try to run npm run webpack, this shows "Error: 'output.filename' is required, either in config file or as --output-filename."
The config file is named correctly as webpack.config.js and is also in the root directory.
Below is the content in the config file:
var path = require('path');
var webpack = require('webpack');
module.exports - {
entry: './app.js',
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node-modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
};
Would really appreciate help
You have a syntax error.
module.exports -
should be:
module.exports =
And btw, you do not need to require webpack in the configuration file.

How can I use webpack with express?

When I try to use webpack with a simple express server I always get TONS of errors:
express.js
'use strict';
var express = require('express');
var path = require('path');
var url = require('url');
// -------- my proxy----------------------
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 8080);
app.use(function logErrors(err, req, res, next) {
console.error(err.stack);
next(err);
}
);
app.listen(app.get('port'), function() {
console.info('Express server started at http://localhost:' + app.get('port'));
});
I get all those errors:
Version: webpack 1.10.0
Time: 1200ms
Asset Size Chunks Chunk Names
outfile 559 kB 0 [emitted] main
chunk {0} outfile (main) 498 kB [rendered]
[0] ../app/server/express2.js 553 bytes {0} [built]
+ 125 hidden modules
WARNING in ../~/express/lib/view.js
Critical dependencies:
78:29-56 the request of a dependency is an expression
# ../~/express/lib/view.js 78:29-56
ERROR in ../~/express/lib/request.js
Module not found: Error: Cannot resolve module 'net' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/lib
# ../~/express/lib/request.js 18:11-25
ERROR in ../~/express/lib/view.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/lib
# ../~/express/lib/view.js 18:9-22
ERROR in ../~/express/~/send/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send
# ../~/express/~/send/index.js 25:9-22
ERROR in ../~/express/~/etag/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/etag
# ../~/express/~/etag/index.js 22:12-25
ERROR in ../~/express/~/send/~/destroy/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send/node_modules/destroy
# ../~/express/~/send/~/destroy/index.js 1:17-30
ERROR in ../~/express/~/send/~/mime/mime.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send/node_modules/mime
# ../~/express/~/send/~/mime/mime.js 2:9-22
ERROR in ../~/express/~/send/~/statuses/codes.json
Module parse failed: /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send/node_modules/statuses/codes.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "100": "Continue",
| "101": "Switching Protocols",
| "102": "Processing",
# ../~/express/~/send/~/statuses/index.js 2:12-35
ERROR in ../~/express/~/send/~/mime/types.json
Module parse failed: /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/send/node_modules/mime/types.json Line 1: Unexpected token :
You may need an appropriate loader to handle this file type.
|
# ../~/express/~/send/~/mime/mime.js 87:12-35
ERROR in ../~/express/~/accepts/~/mime-types/~/mime-db/db.json
Module parse failed: /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "application/1d-interleaved-parityfec": {
| "source": "iana"
| },
# ../~/express/~/accepts/~/mime-types/~/mime-db/index.js 11:17-37
ERROR in ../~/express/~/type-is/~/mime-types/~/mime-db/db.json
Module parse failed: /Users/Dynopia/Development/DS_Stalker_Frontend/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "application/1d-interleaved-parityfec": {
| "source": "iana"
| },
# ../~/express/~/type-is/~/mime-types/~/mime-db/index.js 11:17-37
and this is my config file:
var webpack = require('webpack');
module.exports = {
// Makes sure errors in console map to the correct file
// and line number
devtool: 'eval',
entry: [
'./bin/www.js'
],
output: {
path: './bin/out',
filename: 'server.js'
},
extensions: [
'',
'.jsx', '.js'
],
module: {
loaders: [
// Compile es6 to js.
{
test: /app\/.*\.js?$/,
loaders: [
'react-hot',
'babel-loader'
]
}
]
},
devtool: 'source-map'
};
What can I do, I need to use webpack on my server side as well.
I run the express.js file like so:
./node_modules/webpack/bin/webpack.js ../app/server/express.js outfile --display-chunks -c --progress -d
What I ended up doing was I used 2 different configurations, 1 for packing the server stuff together using webpack, and 1 for packing all the browser stuff together and also run webpack dev server for hot reloading.
Server webpack config aka webpack.node.config.js now looks like this:
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var nodeModules = {};
// note the path.resolve(__dirname, ...) part
// without it, eslint-import-resolver-webpack fails
// since eslint might be invoked with different cwd
fs.readdirSync(path.resolve(__dirname, 'node_modules'))
.filter(x => ['.bin'].indexOf(x) === -1)
.forEach(mod => { nodeModules[mod] = `commonjs ${mod}`; });
// es5 style alternative
// fs.readdirSync(path.resolve(__dirname, 'node_modules'))
// .filter(function(x) {
// return ['.bin'].indexOf(x) === -1;
// })
// .forEach(function(mod) {
// nodeModules[mod] = 'commonjs ' + mod;
// });
module.exports =
{
// The configuration for the server-side rendering
name: 'server',
target: 'node',
entry: './app/server/serverEntryPrototype.js',
output: {
path: './bin/',
publicPath: 'bin/',
filename: 'serverEntryPoint.js'
},
externals: nodeModules,
module: {
loaders: [
{ test: /\.js$/,
loaders: [
// 'imports?document=this',
// 'react-hot',
'babel-loader'
//,'jsx-loader'
]
},
{ test: /\.json$/, loader: 'json-loader' },
]
},
plugins: [
// new webpack.NormalModuleReplacementPlugin("^(react-bootstrap-modal)$", "^(react)$")
// new webpack.IgnorePlugin(new RegExp("^(react-bootstrap-modal)$"))
// new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
};
Browser webpack config aka webpack.browser.config.js now looks like this:
var webpack = require('webpack');
var path = require('path');
var buildPath = path.resolve(__dirname, 'assets');
var fs = require('fs');
var commonLoaders = [
{ test: /\.js$/,
loaders: [
'react-hot',
'babel-loader'
//,'jsx-loader'
]
}
];
module.exports =
{
// Makes sure errors in console map to the correct file
// and line number
name: 'browser',
devtool: 'eval',
entry: [
//'./bin/www.js',
'./app/index.js',
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:8081' // WebpackDevServer host and port
],
output: {
path: buildPath,
filename: '[name].js',
// Everything related to Webpack should go through a build path,
// localhost:3000/build. That makes proxying easier to handle
publicPath: 'http://localhost:8081/assets/'
},
extensions: [
'',
'.jsx', '.js',
'.json',
'.html',
'.css', '.styl', '.scss', '.sass'
],
module: {
loaders: [
// Compile es6 to js.
{
test: /app\/.*\.jsx?$/,
loaders: [
'react-hot',
'babel-loader'
]
},
///app\/.*\.json$/
{ test: /\.json$/, loader: 'json-loader' },
// Styles
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.s(a|c)ss$/, loader: 'style!css?localIdentName=[path][name]---[local]---[hash:base64:5]!postcss!sass' },
// Fonts
{ 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: /\.png$/, loader: 'url-loader?limit=100000' },
//{ test: /\.jpg$/, loader: 'file-loader' }
],
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
},
postcss: [
require('autoprefixer-core')
],
devtool: 'source-map'
}
;
It can be realized by specifying "node" to "target" option, since v1.10.2.
For reference: http://jlongster.com/Backend-Apps-with-Webpack--Part-I
If you want to bundle the server and the client's code at the same time, it is possible to use multiple configuration in the following manner.
// webpack.config.js
module.exports = [
{
name: 'server',
entry: './src/server/index.js',
target: 'node',
output: {
path: __dirname + '/dist/server',
filename: 'bundle.js',
},
},
{
name: 'client',
entry: './src/client/index.js',
// target: 'web', // by default
output: {
path: __dirname + '/dist/client',
filename: 'bundle.js',
},
}
];
I am just clarifying #meta2's answer because I believe it can be written in a more understandable way - although full points to him!
tl;dr - set target: 'node' in your webpack.config.js to fix the errors that get generated when using Webpack with Express.
You still get warnings like:
WARNING in ./node_modules/express/lib/view.js
81:13-25 Critical dependency: the request of a dependency is an expression
To fix those, use https://github.com/liady/webpack-node-externals. FYI - this reduces you bundle size significantly (check size before and after) and speeds up the bundling time incredibly.
Full example:
const path = require('path')
const nodeExternals = require('webpack-node-externals')
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
target: 'node', // THIS IS THE IMPORTANT PART
externals: [nodeExternals()],
mode: 'development'
}
Additionally, if you are working with Typescript, make sure to also include the ".js" extension in your config:
module.exports = {
entry: './src/server/index.ts',
target: 'node',
output: {
path: __dirname + '/dist/server',
filename: 'bundle.js',
},
resolve: {
modules: [
"node_modules"
],
extensions: [".ts", ".js"]
}
};
I took an easy approach that could be useful in a small or medium project. I make it so webpack would serve as the bundler for ecma script and scss, though in this aproach i dont use hot reloading.
The server configuration is the default given by express generator.
webpack.config.js
const path = require("path");
module.exports = {
entry: "./resources/index.js",
output: {
path: path.join(__dirname, "/public/dist"),
publicPath: "/public/dist",
filename: "main.js"
},
mode: "development",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"]
}
]
}
};
package.json is devDependencies
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/preset-env": "^7.6.3",
"babel-loader": "^8.0.6",
"css-loader": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.13.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9"
}
package.json is scripts
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon",
"build": "webpack",
"watch": "webpack --watch"
},
Here is a simple setup to build an express+webpack app. Please pay attention to package.json file scripts part which starts simultaneously express server and webpack process.
And also please pay attention server.js file "app.use(express.static('dist'));" part. Express static should point to webpack folder which contains index.html and bundle.js
server.js file:
const express = require ("express");
const path = require ("path");
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(express.static('dist'));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
})
const server = app.listen (process.env.PORT || 4000);
const portNumber = server.address().port;
console.log("ГОСПОДИН ПОРТ СЕИЧАС ОТКРЫТ "+ portNumber);
now package.json file:
{
"name": "firebase1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"server": "node server.js",
"dev": "concurrently --kill-others-on-fail \"npm run build\" \"npm run server\""
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.64.0",
"webpack-cli": "^4.9.1"
},
"dependencies": {
"express": "^4.17.1"
}
}
Now, webpack.config.js file:
const path = require("path");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
watch: true
}
And finally index.html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FIREBASE PROJECT OF MY LORD TOM AND JERRY</title>
</head>
<body>
<h1>Getting Started with Firebase</h1>
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>

Categories

Resources