UglifyJs error with Gulp and webpack - javascript

I am currently discovering the module bundler "Webpack". I am trying to do something quite easy : I have a main.js entry and a bundle.js output. I use babel in order to translate in ES6.
My package.json :
{
"name": "me",
"version": "1.0.0",
"description": "Builder",
"main": "index.js",
"scripts": {
...
},
"author": "me",
"license": "ISC",
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-env": "^1.5.2",
"babel-preset-es2015": "^6.24.1",
"gulp": "^3.9.1",
"lodash": "^4.17.4",
"webpack": "^3.0.0",
"webpack-stream": "^3.2.0"
},
"dependencies": {
"jquery": "^3.2.1"
}
}
Webpack.config.js :
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, 'js/main.js'),
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015']
}
}
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
}
When I prompt webpack in the CLI, it works pretty well, a bundle.js file which is minified is created in the dist folder.
Now, I want to combine with Gulp
Here is my gulpfile.js :
var gulp = require('gulp');
var webpackS = require('webpack-stream');
gulp.task('default', function() {
return gulp.src('./app/js/main.js')
.pipe(webpackS( require('./app/webpack.config.js') ))
.pipe(gulp.dest('./app/dist/'));
});
When I enter gulp in the CLI, I have this error :
stream.js:74
throw er; // Unhandled stream error in pipe.
^
Error: bundle.js from UglifyJs
Unexpected token: name (_) [bundle.js:47,8]
However, when I remove the line new webpack.optimize.UglifyJsPlugin() from webpack.config.js and prompt gulp in the CLI it works perfectly !
I reinstalled all the npm packages but the problem is still here.
Does anybody have an idea ?

I would like to suggest you to don't mix webpack and gulp,
just create a script inside your package.json#scripts which runs webpack and then if you still want to exec webpack inside a gulp task you can do:
var exec = require('child_process').exec;
gulp.task('runWebpack', function (callback) {
exec('npm run webpack', callback);
})

How do you run the Webpack config? I assume by webpack path-to-config/webpack.config.js?
You have new webpack.optimize.UglifyJsPlugin() in your config, so by using webpack -p which executes the production mode, you get an error because UglifyJsPlugin is executed twice.
I guess the same happens with your Gulp setup.
However, the error message points to "_" not defined, which could be related to lodash. Maybe the import can't be resolved by Gulp?
However, I would not mix Gulp and Webpack. See the discussion here: Gulp + Webpack or JUST Webpack?
There is also an example using Webpack from within a gulp task.

Related

Trying to create readable output bundle but error message:- Entry module not found: Error: Can't resolve './src/index.js'

I am using Webpack version 6.14.8 in an Asp.net Core Razor Pages application in Visual Studio 2019. I am trying to create a readable output file. Here is the structure:-
|-->wwwroot
----->src (created manually)
------->index.js (created manually)
|-->dist (generated by webpack)
------->main.js (webpack bundle)
|-->node_modules (npm init webpack --save-dev)
|-->package.json (npm init -y)
----->package-lock.json (npm init -y)
|-->webpack.config.js (manually configured)
The src/index.js file is blank index.js file.
The package.json: -
{
"name": "aspnet.core",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"wbp": "webpack --entry ./src/index.js --output ./dist/main.js --mode development",
"build": "webpack --config webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"lodash": "^4.17.20",
"startbootstrap-simple-sidebar": "^5.1.2",
"webpack": "^5.1.3",
"webpack-cli": "^4.0.0"
}
webpack.config.js:
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src') + '/path/to/your/file.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
I am trying to create a readable output folder: -"dist/main.js" in wwwroot folder: dist/main.js. However, when I ran the command: npm run wbp, I received the following error message about the entry module could not be found: Error: Can't resolve './src/index.js' in C:\ directory folder: -
C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld >npm run wbp
>helloword#1.0.0 wbp C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld
>webpack ./src/index.js --output ./dist/main.js --mode development
asset main.js 1.47 KiB [emitted] (name: main)
.dist/main.js 644 bytes built] code generated
ERROR in main
Module not found: Error: Can't resolve './src/index.js' in C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld
webpack 5.1.3 compiled with 1 error in 858 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! HelloWorld#1.0.0 build: `webpack --config webpack.config.js --mode development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the HelloWorld#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\xxx\AppData\Roaming\npm-cache\_logs\2020-10-18T07_19_13_940Z-debug.log
C:\Users\xxx\Desktop\My Folder\Visual Studio\Projects\Final\HelloWorld >
The dist/main file was created in the project directory and its contents are: -
/*
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
* This devtool is not neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
/******/ (() => { // webpackBootstrap
/*!**********************!*\
!*** ./dist/main.js ***!
\**********************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: */
eval("/*\n * ATTENTION: The \"eval\" devtool has been used (maybe by default in mode: \"development\").\n * This devtool is not neither made for production nor for readable output files.\n * It uses \"eval()\" calls to create a separate source file in the browser devtools.\n * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)\n * or disable the default devtool with \"devtool: false\".\n * If you are looking for production-ready output files, see mode: \"production\" (https://webpack.js.org/configuration/mode/).\n */\n/******/ (() => { // webpackBootstrap\n/******/ \t\"use strict\";\n/******/ })()\n;\n\n//# sourceURL=webpack://HelloWorld/./dist/main.js?");
/******/ })()
;
I looked at the url address:- https://webpack.js.org/configuration/devtool/, and I tried the "output.path" option: Output|webpack, but it did not work, when I ran the "npm run wbp" command.
How do I fix the issue of input: .src/index.js file is not found and how do I create a readable output: dist/main file?
Thank you in advance.
Current structure:-
|-->wwwroot
----->src (created manually)
------->index.js (created manually)
----->dist (generated by webpack-created by the command: npm run build)
------->main.js (webpack bundle-created by the command: npm run build)
------->index.html (created by the command: npm run build)
|-->node_modules (npm init webpack --save-dev)
|-->package.json (npm init -y)
----->package-lock.json (npm init -y)
|-->webpack.config.js (manually configured)
package.json
"name": "aspnet.core",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "SET NODE_ENV='production' && webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^5.0.0",
"html-webpack-plugin": "^4.5.0",
"lodash": "^4.17.20",
"popper.js": "^1.16.1",
"startbootstrap-simple-sidebar": "^5.1.2",
"style-loader": "^2.0.0",
"webpack": "^5.1.3",
"webpack-cli": "^4.0.0",
"webpack-node-externals": "^2.5.2"
},
"dependencies": {
"#fullcalendar/core": "^5.3.1",
"#fullcalendar/daygrid": "^5.3.2",
"#fullcalendar/list": "^5.3.1",
"#fullcalendar/timegrid": "^5.3.1"
}
}
I updated the input and output files of the webpack.config.js file in development mode as follows: -
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: 'development',
entry: [
'babel-polyfill',
'./wwwroot/src/index.js'
],
output: {
path: path.resolve(__dirname, 'wwwroot/dist'),
filename: 'main.js'
},
resolve: {
extensions: ['.js', '.json']
},
module: {
rules: [
{ test: /\.(js)$/, use: { loader: 'babel-loader', options: {presets: ['#babel/preset-react']} }},
{ test: /\.(sass|scsss|css)$/, use: ['style-loader', 'css-loader'] },
{ test: /\.(svg|eot|woff|woff2|ttf)$/, use: ['file-loader'] },
]
},
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], //in order to ignore all modules in node_modules folder
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin(),
],
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development'
}
and afterwards run the command:- npm run build

Trying to build ReactJS app in prod - Module build failed: SyntaxError: Unexpected token

Its been a while since I've pushed my React app to a prod environment after a bunch of changes (dumb, I know) and now when I try to build it for prod the build is failing and I'm getting the following error:
ERROR in ./src/app.js
Module build failed: SyntaxError: Unexpected token (9:16)
7 |
8 |
> 9 | ReactDOM.render(<AppRouter />, document.getElementById('app'));
| ^
10 |
11 |
# multi #babel/polyfill ./src/app.js
error Command failed with exit code 2.
Here's my webpack.config.js file:
const path = require('path');
module.exports = (env) => {
const isProduction = env === 'production';
console.log(env);
return {
entry: ["#babel/polyfill", "./src/app.js"],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}]
},
devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true
}
};
};
And here's my package.json file:
{
"name": "SheSaysGo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"serve": "live-server public/",
"build:dev": "webpack",
"build:prod": "webpack -p --env production",
"dev-server": "webpack-dev-server",
"start": "node server/server.js"
},
"dependencies": {
"#babel/polyfill": "^7.4.4",
"babel-cli": "6.24.1",
"babel-core": "6.25.0",
"babel-loader": "7.1.1",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"chaituvr-react-graphjs-test": "^0.0.3",
"cosmicjs": "^3.2.17",
"express": "4.15.4",
"google-maps-react": "^2.0.2",
"live-server": "^1.2.1",
"lodash": "^4.17.11",
"react": "16.0.0",
"react-dom": "16.0.0",
"react-leaf-carousel": "^1.2.2",
"react-router-dom": "4.2.2",
"validator": "8.0.0",
"webpack": "3.1.0",
"webpack-dev-server": "2.5.1"
}
}
It builds when I run it locally as a dev build with "yarn run dev-server" but not when I run "yarn run build:prod".
EDIT: Sorry I had written .babel.rc, it's .babelrc
Getting babel-loader to use preset-react
It looks like Babel is interpreting your file as regular JavaScript, as opposed to React JSX (or whatever it's called).
I see in your package.json that you're using #babel/preset-react, so it should work if well configured.
In .babelrc
Check your .babelrc file, it should contain something like this:
{
"presets": ["#babel/preset-react"]
}
You can also change the extension of the file to .jsx, it find it to be clearer, but that's up to your personal preference.
In webpack.config.js
Alternatively, you can define this in the webpack config. Replace this:
loader: 'babel-loader',
with this (in your webpack.config.js):
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
},
Check the package's name
Looking closer at your package.json, it contains:
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
But you're using #babel/preset-env and #babel/preset-react. So npm install --save those and remove the old ones from your package.json.
Run babel --presets #babel/preset-react ./src/app.js, to see if the preset is there and works:
Running it should print to the console:
ReactDOM.render(React.createElement(AppRouter, null), document.getElementById('app'));
^ this is babel successfully converting JSX to JS.

Webpack 4 basic React js hello world fails with "Module parse failed: Unexpected token"

Update:
Code pushed to https://github.com/gsouvik/react_spa_experiment
Initial Post:
I know there are hundreds of threads out there, some had typos in webpack config, some used the loaders in a wrong way, some got it solved, some still open. But after numerous tries I still cannot get this working, a simple "Hello World" using Webpack 4, React js.
What I did
I was following this video tutorial line by line:
React & Webpack 4 from scratch
My package.json
{
"name": "my_react_experiment_2",
"version": "1.0.0",
"description": "Basic react with webpack ",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --mode development --hot",
"build": "webpack --mode production"
},
"author": "Souvik Ghosh",
"license": "ISC",
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
}
My webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.export = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/build'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/templates/index.html'
})
]
};
My .babelrc
{
"presets": ["env", "react"]
}
My directory structure
Expected behaviour
I fire up the dev server npm run dev. Expected to see my shiny new React js page saying "My first React Webpack project" (from the component /components/App.js)
Actual Behavior
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
| import App from "./components/App";
|
ReactDOM.render(, document.getElementById('root'));
| //ReactDOM.render('Hello User ', document.getElementById('root'));
# multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src main2
If required I can share the codebase via a git repo. Any help is greatly appreciated.
The issue is with typo in your webpack config file.
You have module.export which is not correct. It should be module.exports
Working example
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/build'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/templates/index.html'
})
]
};

Issues parsing async functions with webpack

I'm trying to get webpack to parse a javascript file that is using the new async/await syntax, but it keeps giving me a parsing error.
Here is my webpack.config.js file:
module.exports = {
entry: {
foo: './foo.js'
},
output: {
filename: 'webpack-compiled.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
}
My package.json file:
{
"name": "async-func-test",
"version": "1.0.0",
"description": "",
"main": "foo.js",
"scripts": {
"buildWithBabel": "babel foo.js --out-file babel-compiled.js",
"buildWithWebpack": "webpack --progress --colors"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-plugin-syntax-async-functions": "^6.13.0",
"webpack": "^1.13.3"
}
}
My babel.rc file:
{
"plugins": [
"syntax-async-functions"
]
}
And the foo.js file:
async function asyncFunc() {
return 123
}
asyncFunc().then(x => console.log(x))
If I run the npm script 'buildWithBabel', it runs fine with no errors and creates the babel-compiled.js with the proper output.
However if I run the npm script 'buildWithWebpack', I get the following error message:
ERROR in ./foo.js
Module parse failed: C:\Users\Redark\Desktop\asyncFuncTest\node_modules\babel-loader\lib\index.js!C:\Users\Redark\Desktop\asyncFuncTest\foo.js Unexpected token (1:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:6)
I don't need to transform the async functions, just parse it. I'm not sure why it's not working for webpack as it should using the "syntax-async-functions" plugin in the .babelrc right?
You will need to use the transform-regenerator plugin as well, syntax-async-functions only allows Babel to parse the input (and then leave it alone). Webpack doesn't understand ES8 syntax yet, that's why it fails without having them transpiled.

webpack 2: ERROR in ./public/bundle.js from UglifyJs Unexpected character '`'

I got 2 related issues:
First: when I run npm run build the bundle.js file is not minified but I do get a bundle.js.map file.
Second: when I run webpack -d I only get a minified bundle.js file (and no error) but when I run webpack -p then I get a bundle.js that is not minified, a bundle.js.map, and those errors:
ERROR in ./public/bundle.js from UglifyJs
Unexpected character '`' [./app/config.js:5,0][./public/bundle.js:76,14]
ERROR in ./public/bundle.js from UglifyJs
Unexpected character '`' [./app/config.js:5,0][./public/bundle.js:76,14]
My question(s):
shouldn't the behaviors of webpack -p and webpack -d be the
opposite?
why is bundle.js not minified when I run npm run build?
why do I get those Unexpected character errors when I use template strings in my modules?
package.json looks like that:
{
...,
"scripts": {
"build": "webpack --progress --watch"
},
"devDependencies": {
"babel-core": "^6.13.2",
"babel-loader": "^6.2.5",
"babel-preset-es2015-native-modules": "^6.9.4",
"eslint": "^3.3.1",
"eslint-config-airbnb": "^10.0.1",
"eslint-plugin-html": "^1.5.2",
"eslint-plugin-import": "^1.13.0",
"eslint-plugin-jsx-a11y": "^2.1.0",
"eslint-plugin-react": "^6.1.2",
"webpack": "^2.1.0-beta.21"
}
}
while webpack.config.js is like that:
const webpack = require('webpack'); // eslint-disable-line import/no-extraneous-dependencies
const nodeEnv = process.env.NODE_ENV || 'production';
module.exports = {
entry: {
filename: './app/app.js'
},
output: {
filename: './public/bundle.js'
},
modules: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015-native-modules']
}
}
]
},
devtool: 'source-map',
plugins: [
// uglify
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
output: { comments: false },
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
})
]
};
I did search both here and Google (and webpack docs…) but I can't find anything useful to me. Thanks!!
UglifyJS2 does not have ES6/Harmony support in its releases yet. However, there's the Harmony branch which allows you to minify/uglify files with ES6 syntax.
I can suggest you an alternative solution which could help you spend less build time to transpile all ES6 to ES5.
Simply specify UglifyJs in your package.json, and let npm handles the dependencies.
"uglify-js": "git://github.com/mishoo/UglifyJS2#harmony-v2.8.22",

Categories