The webpack -p cli command fails to uglify es2015 code
package.json
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.13.2",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.13.2"
}
webpack.config.js
var webpack = require("webpack");
var config = {
entry: './src/app.js',
devtool: "source-map",
output: {
path: '../Scripts',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
},
include: ["./src"],
exclude: /node_modules/
}
]
}
}
module.exports = config;
Error when running webpack -p
ERROR in bundle.js from UglifyJs
Unexpected character '`' [./src/LineEndRenderer.js:33,0]
(es2015 template string use)
Running webpack -d works fine.
A user (fulls1z3) at github came up with a solution that does not require babel (see post from 11/26/2016):
Here is a copy:
webpack#2 users, I'm hereby trying to help by providing detailed instructions to use the Harmony branch of UglifyJs2 with webpack:
Fork webpack,
On that fork, delete all branches except master,
Clone master branch to a local folder,
On the local folder, delete all files,
Commit the empty local folder,
Download the latest release (ex: v2.1.0-beta.27 at the moment)
Extract contents of zip file to the local folder,
On the local folder, edit forked package.json, change
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"
to point UglifyJs2 (harmony branch) dependency to that branch.
Commit changes,
Finally, point webpack in your package.json to your custom fork:
"webpack": "[USERNAME]/webpack#master"
OR,
Point webpack in your package.json to fulls1z3/webpack (ES6/ES2015 friendly webpack fork):
"webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"
I was using webpack globally, so I had to run this too:
npm install yargs supports-color enhanced-resolve interpret tapable webpack-sources source-map uglify-js object-assign async loader-runner acorn watchpack mkdirp ajv ajv-keywords node-libs-browser -g
Then I replaced my global webpack npm folder with webpack-2.1.0-beta.27-harmony.zip from https://github.com/fulls1z3/webpack/releases
Lastly, I replaced my global uglify-js npm folder with UglifyJS2-harmony.zip from https://github.com/mishoo/UglifyJS2/tree/harmony
Related
I got the following lines in my package.json file (I just mirrored courses teacher)
"scripts": {
"build:dev": "env NODE_ENV=development webpack --config webpack.config.js",
"build:prod": "env NODE_ENV=production webpack --config webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
But unlike for him it doesn't work for me, when I point my mouse to a build word (both of them), and click "Run Script" I get this error:
Executing task: npm run build:dev
/usr/bin/bash: line 1: npm: command not found
* The terminal process "/usr/bin/bash '-c', 'npm run build:dev'" failed to launch (exit code: 127).
* Terminal will be reused by tasks, press any key to close it.
I certainly see no clues about that issue, and can't find them on the internet.
I have npm installed, and wondering what's wrong. Maybe webpack is bad configured, but If I just run
Webpack
in my console it compiles successfully. Anyway here is my webpack.config.js file:
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const NODE_ENV = process.env.NODE_ENV;
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json']
},
mode: NODE_ENV ? NODE_ENV : 'development',
entry: path.resolve(__dirname, 'src/index.jsx'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
},
module: {
rules: [{
test: /\.[tj]sx?$/,
use: ['ts-loader']
}]
},
plugins: [
new HTMLWebpackPlugin({ template: path.resolve(__dirname, 'index.html') })
]
};
By the way, I have one problem in my project that may somehow affect mentioned problem (that isn't likely though). I've typed
tsc --init
to create tsconfig.json file and here is vscode problem warning:
`JSON schema for the TypeScript compiler's configuration file
Cannot write file '/home/timothy/Desktop/WEB_COURSE/dist/index.js' because it would overwrite input file.ts
Cannot write file '/home/timothy/Desktop/WEB_COURSE/dist/index.js' because it would overwrite input file.ts`
I didn't try to resolve this issue yet, because I really don't know what even should I do.
Background
I'm using react, babel, webpack4, and es6(or maybe es7)
I have some modules that are reused by multiple react projects. For this reason I've created a 'Standard' folder that contains these modules so that they are kept separate from any specific project.
Problem
In my react project I edited my webpack.config.js to contain
resolve: {
extensions: ['.css', '.js', '.jsx'],
alias: {
Standard: '/Path/To/Standard',
}
}
Then to import a module from it I call
import MyModule from 'Standard/MyModule.js'
When I do this, it looks like the html tags aren't recognized within the files in my Standard folder
Error Messages
For webpack-dev-server --inline
ERROR in /Path/To/Standard/MyModule.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Path/To/Standard/MyModule.js: Unexpected token (13:8)
11 | var MyModule = (props) => {
12 | return (
> 13 | <header id='Header' className={props.className}>
For webpack
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! default#1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the default#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Debugging attempts
I've tried to create a webpack.config.js and package.json inside my standard folder(in addition to my project folder), but nothing really seems to help
I tried some npm installs to install babel, because that seemed like the most obvious solution, and is used on this answer in an older webpack version, but I still get the same problems
npm install --save react
npm install --save babel #babel/cli #babel/core #babel/preset-env #babel/preset-react
npm install --save babel-core babel-loader babel-cli babel-preset-env babel-preset-react webpack
Also it looks like this post which is a reply to this blog might be related, but this solution didn't work for me.
package.json
{
"scripts": {
"webpack": "webpack",
"start": "http-server"
},
"dependencies": {
"react": "^16.8.6"
},
"devDependencies": {
"#babel/cli": "^7.5.5",
"#babel/core": "^7.5.5",
"#babel/plugin-proposal-object-rest-spread": "^7.5.1",
"#babel/polyfill": "^7.4.4",
"#babel/preset-env": "^7.5.0",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"webpack": "^4.28.0"
}
}
webpack.config.js
var webpack = require('webpack');
const config = {
mode: 'development', // set mode option, 'development' or 'production'
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
resolve: {
extensions: ['.css', '.js', '.jsx'],
}
}
module.exports = config;
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
You're 1st problem here is that babel is not parsing code from you're packages (error say that it try to exec not transpiled jsx code).
Maybe the babel presets is not accessible in you're package directory.
You can try copying them or set them directly in the webpack config
{
loader : 'babel-loader',
options: {
presets : [
['#babel/preset-env',
{// here the presets params
}],
'#babel/preset-react'
],
plugins : [
['#babel/plugin-proposal-class-properties', {
"loose": true
}]
]
}
},
Possibly the exclude regexp of babel exclude the packages from where you want importing scripts :
exclude: /(node_modules|bower_components)/,
So you can use a custom function like that :
exclude: {test:(pathName)=>(isInternalCode(pathName))),
Or use negative lookahead in the reg exp like :
/(node_modules(?!\b(?:OneFolder|AnotherIncluded))|bower_modules)/
That's said the usual way is to compile independently you're packages ( by externalizing all theirs deps from the builds & adding them to "peerDependencies" or "dependencies" )
Also; there a plugin to make "inheritable" packages; layer-pack.
It allow making "inheritable" projects, & deal with node_modules & webpack to make inheritable "code layers" & even work when compiling node scripts or using monorepo structure
Using it you can simply put you're components in a shared inheritable package
it come with some nice features like glob resolving, which help including an unknown number of files.
There is samples here & doc here
Hope it help :)
I'm trying to get my Node application to start with npm start. The application is crashing on start and I do not know why. I am really new to Node and all things full-stack. Can anybody make sense of whats going on?
When I run npm start --verbose I get this:
hunterhawley#hunter-test:~$ npm start --verbose
npm info it worked if it ends with ok
npm verb cli [ '/home/hunterhawley/.nvm/versions/node/v11.10.1/bin/node',
npm verb cli '/home/hunterhawley/.nvm/versions/node/v11.10.1/bin/npm',
npm verb cli 'start',
npm verb cli '--verbose' ]
npm info using npm#6.7.0
npm info using node#v11.10.1
npm verb config Skipping project config: /home/hunterhawley/.npmrc. (matches userconfig)
npm verb run-script [ 'prestart', 'start', 'poststart' ]
npm info lifecycle mern-starter#2.0.0~prestart: mern-starter#2.0.0
npm info lifecycle mern-starter#2.0.0~start: mern-starter#2.0.0
> mern-starter#2.0.0 start /home/hunterhawley
> cross-env BABEL_DISABLE_CACHE=1 NODE_ENV=development nodemon index.js
[nodemon] 1.17.5
[nodemon] reading config ./nodemon.json
[nodemon] to restart at any time, enter `rs`
[nodemon] or send SIGHUP to 31462 to restart
[nodemon] ignoring: .git node_modules/**/node_modules
[nodemon] watching: /home/hunterhawley/server/**/* Intl
[nodemon] watching extensions: js,json
[nodemon] starting `node index.js`
[nodemon] forking
[nodemon] child pid: 31475
[nodemon] watching 37 files
/home/hunterhawley/node_modules/babel-core/lib/transformation/file/index.js:558
throw err;
^
SyntaxError: /home/hunterhawley/server/server.js: Unexpected token (164:8)
162 | const store = configureStore({
163 | app: {
> 164 | ...initialAppState,
| ^
165 | user: { ...req.session.user },
166 | },
167 | });
at Parser.pp$5.raise (/home/hunterhawley/node_modules/babylon/lib/index.js:4454:13)
at Parser.pp.unexpected (/home/hunterhawley/node_modules/babylon/lib/index.js:1761:8)
at Parser.pp$3.parseIdentifier (/home/hunterhawley/node_modules/babylon/lib/index.js:4332:10)
at Parser.pp$3.parsePropertyName (/home/hunterhawley/node_modules/babylon/lib/index.js:4156:96)
at Parser.pp$3.parseObj (/home/hunterhawley/node_modules/babylon/lib/index.js:4045:12)
at Parser.pp$3.parseExprAtom (/home/hunterhawley/node_modules/babylon/lib/index.js:3719:19)
at Parser.pp$3.parseExprSubscripts (/home/hunterhawley/node_modules/babylon/lib/index.js:3494:19)
at Parser.pp$3.parseMaybeUnary (/home/hunterhawley/node_modules/babylon/lib/index.js:3474:19)
at Parser.pp$3.parseExprOps (/home/hunterhawley/node_modules/babylon/lib/index.js:3404:19)
at Parser.pp$3.parseMaybeConditional (/home/hunterhawley/node_modules/babylon/lib/index.js:3381:19)
[nodemon] app crashed - waiting for file changes before starting...
So it seems to me that this is a babel issue. I can attach my index.js or any other file if that will help you figure this out. Thank you!
EDIT: Also I just wanted to add that the install process (though it took some work) went smoothly, and I have MongoDB running in another terminal window, which for this application is needed. I've also tried going direct and running node index.js but that didn't get me anywhere either.
EDIT 2: Here is what I got when installing the plugin given in answer 1
npm WARN babel-plugin-webpack-loaders#0.9.0 requires a peer of webpack#>=1.12.9 <3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN chunk-manifest-webpack-plugin#0.1.0 requires a peer of webpack#^1.4.0-beta6 but none is installed. You must install peer dependencies yourself.
npm WARN extract-text-webpack-plugin#1.0.1 requires a peer of webpack#^1.9.11 but none is installed. You must install peer dependencies yourself.
npm WARN webpack-dev-middleware#1.12.2 requires a peer of webpack#^1.0.0 || ^2.0.0 || ^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN webpack-dev-server#2.11.2 requires a peer of webpack#^2.2.0 || ^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN webpack-manifest-plugin#1.3.2 requires a peer of webpack#1 || 2 || 3 but none is installed. You must install peer dependencies yourself.
npm WARN #babel/plugin-proposal-object-rest-spread#7.3.4 requires a peer of #babel/core#^7.0.0-0 but none is installed. You must install peer dependencies yourself.
npm WARN #babel/plugin-syntax-object-rest-spread#7.2.0 requires a peer of #babel/core#^7.0.0-0 but none is installed. You must install peer dependencies yourself.
npm WARN mern-starter#2.0.0 No repository field.
+ #babel/plugin-proposal-object-rest-spread#7.3.4
added 3 packages from 1 contributor and audited 20460 packages in 22.759s
EDIT 3: Adding my webpack.config.babel.js file
var cssnext = require('postcss-cssnext');
var postcssFocus = require('postcss-focus');
var postcssReporter = require('postcss-reporter');
var cssModulesIdentName = '[name]__[local]__[hash:base64:5]';
if (process.env.NODE_ENV === 'production') {
cssModulesIdentName = '[hash:base64]';
}
module.exports = {
output: {
publicPath: '/',
libraryTarget: 'commonjs2',
},
resolve: {
extensions: ['', '.js', '.jsx'],
modules: [
'client',
'node_modules',
],
},
module: {
loaders: [
{
test: /\.css$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader?localIdentName=' + cssModulesIdentName + '&modules&importLoaders=1&sourceMap!postcss-loader',
},
{
test: /\.jpe?g$|\.gif$|\.png$|\.svg$/i,
loader: 'url-loader?limit=10000',
},
],
},
postcss: () => [
postcssFocus(),
cssnext({
browsers: ['last 2 versions', 'IE > 10'],
}),
postcssReporter({
clearMessages: true,
}),
],
};
Easiest solution is update to Node v8.3 or higher...
"As of Node v8.3, object rest/spread is available without the need for any transpilation."
If you're transpiling using Babel, as you mentioned, then you'll need to add a plugin to polyfill support for Object spread. In your .babelrc file add...
"plugins": [
"#babel/plugin-proposal-object-rest-spread"
]
And you'll need to install this plugin obviously...
npm i -D #babel/plugin-proposal-object-rest-spread
//OR
yarn add #babel/plugin-proposal-object-rest-spread --dev
NOTE: This will require "#babel/core": "^7.0.0"
Here is an example of how to configure your .babelrc file for node transpiling...
{
"presets": [
["#babel/env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-proposal-class-properties"
]
}
You can also add the plugin directly within you Webpack config (webpack.config.babel.js)...
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['#babel/plugin-proposal-object-rest-spread']
}
}
}
]
Example of specific packages (in package.json) I'm currently using in a Node/Babel project, which may help upgrading to Babel ^7.0.0...
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.2.2",
"#babel/plugin-proposal-object-rest-spread": "^7.3.1",
"#babel/plugin-proposal-class-properties": "^7.3.4",
"#babel/preset-env": "^7.3.1",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^24.0.0",
"babel-loader": "^8.0.5",
"babel-plugin-module-resolver": "^3.2.0"
}
Greetings one and all,
After having made a React application, I decided to dive in deeper into Webpack.
I am rather new at the whole npm automation scene and after having followed a cookbook and various tutorials, I just cannot let npm run dev bundle my application. It generates a bundle.js perfectly fine when I run webpack, but what appealed to me was having webpack generate a physical file whenever I change something. Gulp and Grunt can do this for me, but I'd like to get it to work with webpack as well.
So, without further ado, some code. I run npm run dev which is defined like so (package.json, just the scripts part*):
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
}
With the following Webpack configuration:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src/js/main.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: '/js/bundle.js',
publicPath: '/'
},
devServer: {
inline: true,
contentBase: './dist'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
], ["normal"], "loader")
]
};
Cases:
webpack: Bundles my application into dist/js/bundle.js perfectly fine.
webpack-dev-server: Seems to stream a memory bundle from my JS perfectly fine, but does not generate a bundle on disk.
npm run dev: Starts the webpack server, but does not result in a bundle, nor does my application run, resulting in a Cannot GET/ error.
Can anyone point me in the right direction? I have tried variations on the config, but to no avail.. And just to be complete, I will show my directory structure:
./project
./dist
./js
./bundle.js
./src
./js
./main.js
./package.json
./webpack.config.js
Once again, thanks for the assist!
It is due to wrongly written scripts in package.json file. Replace your scripts with the below. It is because you are not providing the correct path to your bundle.js file which is need to be create. "-p" means to read the entry and output keys of webpack.config.js. Then run this cmd: $ npm run build
"scripts": {
"build": "webpack -p",
"dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
}
For me the problem was with package.json under that "scripts"
Here is the fix:
Inside your package.json file, under script add the following:
"scripts": {
"start": "webpack-dev-server",
"build": "webpack -p"
}
First I ran the build then start.
yarn build
if you first build then your bundle.js file will be created and after that you can use this command:
yarn start
Instead of yarn, you can also use npm
I'm trying to run webpack on my postinstall script in my package.json when I push to heroku but I am getting the following error.
ERROR in Entry module not found: Error: Cannot resolve module 'babel-loader' in /tmp/build_6cb4b10367d9382367ab72f2e2f33118
When I run the command locally I get no issues. Below is my webpack config - i have tried using resolveLoader to fix the resolving issue but to no avail?
var path = require('path');
var webpack = require('webpack');
var config = {
entry: path.resolve(__dirname, './app/main.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.less$/,
loader: 'style!css!less'
}]
},
resolve: {
extensions: ['', '.js', '.jsx', '.less'],
modulesDirectories: [
'node_modules'
]
},
resolveLoader: {
root: path.resolve(__dirname, 'node_modules')
},
plugins: [
new webpack.optimize.UglifyJsPlugin({minimize: true})
]
};
module.exports = config;
Any suggestions? Thanks
I found out why. I didn't have babel or babel-core in my package.json. Add them fixed the error.
"devDependencies": {
"babel": "^5.8.23",
"babel-core": "^5.0.0",
"babel-loader": "^5.3.2"
}
In my case, I had mis-spelled the loader while installing it, so make sure you install
babel-loader
NOT
bable-loader
In my case, I tried the command:
$ npm install babel-loader --save
and continued to fix the rest based on the reminder from the console, and it fixed the issue:
"ERROR in Entry module not found: Error: Can't resolve 'babel-loader'"
I had a similar error when working on a Rails 6 application.
I think the issue was that the Babel-loader node package wasn't installed properly or the executable couldn't be located by the application.
All I had to do was to upgrade the node packages in the application by running:
yarn upgrade
Here's my devDependencies in my package.json file:
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0
Note: I didn't have to include Babel-loader node package in the list of devDependencies for it to work.
I'm using yarn and webpacker for a rails + react project.
I know not everyone can upgrade all their dependencies without breaking things, but for me, adding running yarn upgrade fixed this error.
That was with only #babel/core in my dependencies config, since babel-loader is included as a dependency of webpacker.
In some cases, when deploying to production (for example with Rails Webpacker), dev dependencies are not loaded. So having babel-loader in devDependencies will not work.
In fact, it makes sense that babel-loader would be placed in dependencies, not devDependencies, because it's used in the production code itself. The only packages that should be in devDependencies are those that are run in development, such as tests and linters.
I had mine in devDependencies and it didn't work, I switched it to dependencies and it finally worked!
I deleted the yarn.lock and node_modules folder then omit babel-loader in your devDependencies in package.json, then i rerun yarn, and it works.
When using yarn 2, webpack 4 is unable to resolve the loader. or update to webpack 5
I had to use PnPify to make it work.
yarn pnpify webpack
In my case react-scripts was importing babel-loader as dependency. It worked for a while because it was in package-lock.json. If you have react-scripts in your deps, try removing node_modules, package-lock.json and do npm install again.