Issue with Setting Up Webpack and Babel - javascript

I have followed every instruction for setting up webpack and babel. I Installed the dependencies with npm install --save-dev webpack webpack-dev-server #babel/core babel-loader #babel/preset-env #babel/polyfill. I also installed the webpack-cli.
Here is what I have in my package.json file:
{
"name": "webpack_babel_prac",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "wepack-dev-server --mode development --open",
"build": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.12.3",
"#babel/polyfill": "^7.12.1",
"#babel/preset-env": "^7.12.1",
"babel-loader": "^8.1.0",
"webpack": "^5.3.0",
"webpack-cli": "^4.1.0",
"webpack-dev-server": "^3.11.0"
}
}
The following codes are the ones I have in my webpack.config.js file
const path = require('path');
module.exports = {
entry: {
app: ['#babel/polyfill','./src/app.js']
},
output:{
path: path.resolve(__dirname, 'build'),
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query:{
presets: ['#babel/preset-env']
}
}
]
}
}
when I run build (npm run build) it always gives me error:
> webpack_babel_prac#1.0.0 build /Users/sel/Desktop/js_course/webpack_babel_prac
> webpack
[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
- configuration.module.rules[0] has an unknown property 'query'. These properties are valid:
object { compiler?, dependency?, descriptionData?, enforce?, exclude?, generator?, include?, issuer?, loader?, mimetype?, oneOf?, options?, parser?, realResource?, resolve?, resource?, resourceFragment?, resourceQuery?, rules?, sideEffects?, test?, type?, use? }
-> A rule description with conditions and effects for modules.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! webpack_babel_prac#1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the webpack_babel_prac#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! /Users/sel/.npm/_logs/2020-10-29T18_12_00_720Z-debug.log
sels-MacBook-Air:webpack_babel_prac sel$
It's telling me that the configuration has has an unknown property "query" as shown above. When I remove query and leave presets: ['#babel/preset-env']. It will display configuration has has an unknown property "preset". However, when I remove query and presets object it will run build but in my app.bundle.js, the codes from my app.js file are not completely compiled into ES5.
I would I appreciate it if anyone can tell me what I'm doing wrong.
Thanks.

The babel-loader docs show several examples of how to do this. If you're following guides and seeing this, they must be guides that were written several years ago.
query should be options.
module: {
rules: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options:{
presets: ['#babel/preset-env']
}
}
]
}

Related

I am running into an error with an npm command in react. "ERROR in main Module not found: Error: Can't resolve ..."

I have been following a django-react tutorial and ran into a problem with the command npm run dev. I thought it was a problem with the webpack file but maybe not.
[error message][1]
[webpack file][2]
[package.json][3]
[file structure and app.js][4]
[index.js][5]
This is the error that I am receiving:
[1]: https://i.stack.imgur.com/vCK8g.png
(django_venv) C:\Users\bostm\Documents\CodingProjects\React-Django
\music_controller\frontend>npm run dev
> frontend#1.0.0 dev
> webpack --mode development --watch
[webpack-cli] Compilation starting...
[webpack-cli] Compilation finished
asset main.js 0 bytes [compared for emit] [minimized] (name: main)
ERROR in main
Module not found: Error: Can't resolve './src/index.js' in 'C:\Users\bostm
\Documents\CodingProjects\React-Django\music_controller\frontend'
webpack 5.10.2 compiled with 1 error in 136 ms
[webpack-cli] watching files for updates...
This is the webpack file. I assumed the problem was here because the error message said that it couldn't resolve "./src/index.js" in the path to the frontend directory, which is the name of the webapp folder that src/index is in. I tried using a solution from another post by using path.resolve(__dirname, /path/). It did not work so this is what I had originally.
[2]
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./static/frontend"),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
],
},
optimization: {
minimize: true,
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
// This has effect on the react lib size
NODE_ENV: JSON.stringify("production"),
},
}),
],
};
This is the package.json file. The only lines I added were for "dev" and "build."
[3]: https://i.stack.imgur.com/Yea1b.png
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.10",
"#babel/preset-react": "^7.12.10",
"babel-loader": "^8.2.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"webpack": "^5.10.2",
"webpack-cli": "^4.2.0"
},
"dependencies": {
"#babel/plugin-proposal-class-properties": "^7.12.1",
"#material-ui/core": "^4.11.2",
"#material-ui/icons": "^4.11.2",
"react-router-dom": "^5.2.0"
}
}
This is my app.js file The screenshot is included mostly so that you can see how the file directory is setup and I was not sure how to include that as text in the post itself.
[4]: https://i.stack.imgur.com/dLBXd.png
Lastly the index.js file which is just a single line importing App from components.
[5]
import App from "./components/App";
Sorry if anything about my problem is unclear let me know if I can clarify anything. Any help or suggestions would be greatly appreciated. I'm really not sure where I went wrong. I have been considering going back and just creating the react app using npx create-react-app [appName], but I would like to know how to set it up manually in case I want to use something other than babel and webpack in the future. Thanks again.

Vuejs 3 webpack : Problem with vue-template-compiler

I am trying to integrate vuejs 3 to an existing project which uses webpack. I read about vue-loader, so I am trying to use it.
In the official documentation I have this:
Every time a new version of vue is released, a corresponding version of vue-template-compiler is released together. The compiler's version must be in sync with the base vue package so that vue-loader produces code that is compatible with the runtime. This means every time you upgrade vue in your project, you should upgrade vue-template-compiler to match it as well.
So, when I try to compile I get this error:
Vue packages version mismatch:
- vue#3.0.2 (/home/alejo/playground/parquesFrontend/node_modules/vue/index.js)
- vue-template-compiler#2.6.12 (/home/alejo/playground/parquesFrontend/node_modules/vue-template-compiler/package.json)
This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader#>=10.0, simply update vue-template-compiler.
If you are using vue-loader#<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.
But when I try to install vue-template-compiler#3.0.2 I get this error:
❯ npm install vue-template-compiler#3.0.2
npm ERR! code ETARGET
npm ERR! notarget No matching version found for vue-template-compiler#3.0.2.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/alejo/.npm/_logs/2020-11-17T02_52_46_458Z-debug.log
How can I solve this problem?
To make vue 3 work fine with webpack without using vite or vue cli follow these steps :
init the package.json like :
{
"private": true,
"name": "vue-3",
"description": null,
}
install the last version of vue :
npm i --save vue#next vue-loader#next
install also the dev dependencies that includes #vue/compiler-sfc which replaces vue-template-compiler
npm i -D #vue/compiler-sfc css-loader file-loader mini-css-extract-plugin
url-loader webpack webpack-cli webpack-dev-server
#vue/compiler-sfc
css-loader
file-loader
mini-css-extract-plugin
url-loader
vue-loader
webpack
webpack-cli
webpack-dev-server
create or edit your webpack.config.js with following content :
const path = require("path");
const { VueLoaderPlugin } = require("vue-loader");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = (env = {}) => ({
mode: env.prod ? "production" : "development",
devtool: env.prod ? "source-map" : "cheap-module-eval-source-map",
entry: [
require.resolve(`webpack-dev-server/client`),
path.resolve(__dirname, "./src/main.js")
].filter(Boolean),
output: {
path: path.resolve(__dirname, "./dist"),
publicPath: "/dist/"
},
resolve: {
alias: {
// this isn't technically needed, since the default `vue` entry for bundlers
// is a simple `export * from '#vue/runtime-dom`. However having this
// extra re-export somehow causes webpack to always invalidate the module
// on the first HMR update and causes the page to reload.
vue: "#vue/runtime-dom"
}
},
module: {
rules: [
{
test: /\.vue$/,
use: "vue-loader"
},
{
test: /\.png$/,
use: {
loader: "url-loader",
options: { limit: 8192 }
}
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: { hmr: !env.prod }
},
"css-loader"
]
}
]
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css"
})
],
devServer: {
inline: true,
hot: true,
stats: "minimal",
contentBase: __dirname,
overlay: true,
injectClient: false,
disableHostCheck: true
}
});
Add dev script to run your app :
{
"private": true,
"scripts": {
"dev": "webpack-dev-server"
},
"dependencies": {
"vue": "^3.0.2"
},
"name": "vue-3",
"description": null,
"devDependencies": {
...
}
}
Fill the index.html with following content :
<link rel="stylesheet" href="/dist/main.css" />
<div id="app"></div>
<script src="/dist/main.js"></script>
Finally run npm run dev the visit http://localhost:8080/
for a ready to use project try to clone this REPOSITORY which built by following the steps above.
I believe you need to use vue-loader#next with Vue 3
In Vue 3 the SFC compiler package is no longer vue-template-compiler but compiler-sfc (check here)
I completely agree with the suggestion to use Vue CLI to manage the project - it will save you lot of trouble managing all the dependencies (especially now when Vue 3 ecosystem is trying to catch-up with Vue 3 release and lots of tool even don't have any migration documentation ....like vue-loader)
If you are not able to use CLI because your existing project already have Webpack config, you can still use CLI as a guide. Just generate new project on the side, use vue inspect command to inspect Webpack config it is using and package.json for required dependencies...
I've just installed the Webpacker gem in rails that comes with nice tasks that install Vue.
Nevertheless, it installs Vue 2.x with its loader and template compiler...
To bump everything to Vue 3 aand its dependencies simply run:
yarn add vue#next vue-loader#next #vue/compiler-sfc
Voila! You're using Vue 3 now
I upgraded a Vue2 app to Vue3 manually and I was getting this error when I was running the unit tests after upgrading all of the dependencies.
To get everything working, I also had to fix Jest's config file.
In jest.config.js set the "transform" property to:
{
transform: '^.+\\.vue$': `vue-jest`
}
The dependencies I used to get started were from a new Vue3.0 app I created using the cli. Below are the dependencies that my cli settings got me:
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-plugin-router": "~4.5.0",
"#vue/cli-plugin-unit-jest": "~4.5.0",
"#vue/cli-plugin-vuex": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"#vue/test-utils": "^2.0.0-0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0-0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.2",
"typescript": "~3.9.3",
"vue-jest": "^5.0.0-0"
}
Note that for my cli settings, the .eslintrc.js also has some minor changes in it for Vue3. In a fresh install the cli makes the "extends" property as below:
extends: [
`plugin:vue/vue3-essential`,
`eslint:recommended`
],

Why is my webpack bundle successfully built on host machine but is not in docker container?

I have a monorepo structure of my project like this:
babel.config.js
a-something
b-something
where I have the babel config file in the root of my project and the packages a-something and b-something.
Inside package a-something I have the following webpack config:
const path = require('path')
module.exports = {
target: 'node',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.js?$/,
use: {
loader: 'babel-loader',
options: {
rootMode: 'upward'
}
},
include: [
path.resolve(__dirname, 'src'),
/node_modules\/a-/,
/node_modules\/b-/
]
}
]
}
}
Inside the package a-something I have the following package.json:
{
"name": "a-something",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"prod:build": "webpack --config webpack.config.js",
"prod:start": "node build/bundle.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.2",
"graphql": "^14.5.8",
"graphql-request": "^1.8.2",
"graphql-tag": "^2.10.1",
"b-something": "^1.0.0",
"node-fetch": "^2.6.0",
"sitemap": "^5.0.0"
},
"devDependencies": {
"webpack": "3.5.6",
"#babel/polyfill": "7.7.0"
}
}
My root package.json has the following dependencies:
"#babel/cli": "^7.5.5",
"#babel/core": "^7.5.5",
"babel-loader": "8.0.6"
and lastly my Dockerfile inside package a-something is:
FROM node:10.15.1
COPY ./package.json /src/package.json
ENV PORT 3000
ENV NODE_ENV production
WORKDIR /src
RUN npm install
COPY ./lerna.json /src/lerna.json
COPY ./packages/a-something/package.json /src/packages/a-something/package.json
COPY ./packages/b-something/package.json /src/packages/b-something/package.json
RUN npm run clean
COPY . /src
WORKDIR /src/packages/a-something
RUN npm run prod:build
RUN echo "FINISHED BUILDING!"
EXPOSE ${PORT}
CMD ["npm" , "run", "prod:start"]
When I run npm run prod: build and npm run prod: start the bundle is built successfully, however when I build the docker (where the context is the root folder) I get the following npm error:
ERROR in Entry module not found: Error: Can't resolve 'babel-loader' in '/src/packages/a-something'
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! a-something#1.0.0 prod:build: `webpack --config webpack.config.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the a-something#1.0.0 prod:build script.
My host machine OS is macOS Mojave. Maybe the symlinks generated by Lerna are handled differently on Debian (used by node image)?
UPDATE: the issue was resolved by moving all babel related npm packages from devDependencies to dependencies section of root package.json. Does anyone have an idea why this would solve the problem?
As I mentioned in the update section of my question the solution was to move all babel related packages to devDependencies section of the root package.json.
But why did this help?
The problem was I set NODE_ENV to production in Dockerfile. npm will not install dev dependencies if NODE_ENV is set to production. On the host machine I didn't have such variable. In addition another issue would've been #babel/polyfill, according to babel docs:
Because this is a polyfill (which will run before your source code),
we need it to be a dependency, not a devDependency
According to the docs #babel/polyfill is also deprecated so the better solution is to:
add "babel-loader": "8.0.6" to root package.json
Have the following devDependencies in a-something package.json:
"devDependencies": {
"webpack": "3.5.6",
"core-js": "^3.4.7",
"regenerator-runtime": "^0.13.3"
}
Place these 2 lines in the entry Javascript file at the very top:
import 'core-js/stable'
import 'regenerator-runtime/runtime'
Finally use this webpack config:
const path = require('path')
module.exports = {
target: 'node',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.js?$/,
use: {
loader: 'babel-loader',
options: {
rootMode: 'upward',
presets: [
['#babel/preset-env', {
corejs: 3,
useBuiltIns: 'usage'
}]
]
}
},
include: [
path.resolve(__dirname, 'src'),
/node_modules\/a-/,
/node_modules\/b-/
]
}
]
}
}

How to fix "Module build failed (from ./node_modules/babel-loader/lib/index.js):"?

So I have been trying to setup React Js environment. I am facing the babel dependencies error. I know this problem is very common and there are tons of answers available but none of them have worked for me so far.
I have searched through the internet to solve it but it still shows the same error.
This is the error I am getting:
ERROR in ./main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module 'babel-preset-es2015' from 'D:\my-app'
at Function.module.exports [as sync] (D:\my-app\node_modules\resolve\lib\sync.js:58:15)
at resolveStandardizedName (D:\my-app\node_modules\#babel\core\lib\config\files\plugins.js:101:31)
at resolvePreset (D:\my-app\node_modules\#babel\core\lib\config\files\plugins.js:58:10)
at loadPreset (D:\my-app\node_modules\#babel\core\lib\config\files\plugins.js:77:20)
at createDescriptor (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:154:9)
at items.map (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:109:50)
at Array.map (<anonymous>)
at createDescriptors (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:109:29)
at createPresetDescriptors (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:101:10)
at passPerPreset (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:58:96)
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 448 bytes {0} [built]
[./node_modules/lodash/lodash.js] 527 KiB {0} [built]
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
[./node_modules/webpac
This is my .babelrc
{
"presets": ["es2015"]
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1"
},
"devDependencies": {
"#babel/core": "^7.4.4",
"#babel/preset-env": "^7.4.4",
"#babel/preset-es2015": "^7.0.0-beta.53",
"babel-loader": "^8.0.6",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.31.0"
}
}
babel-loader#8.x uses Babel 7.x, which is #babel/core#^7.0.0, and more importantly in your case #babel/preset-env#7 replaces babel-preset-env#^1.7.0.
You'll need to make sure to do
npm install #babel/core #babel/preset-env
and update your Babel config to use #babel/preset-env instead of babel-preset-env with something like
"presets": [
"#babel/preset-env"
]
Note: For others coming across this, the issue may also be that you're using plugins/preset from Babel 6 on Babel 7. This may be hard to notice if you're using a third-party Babel preset since the versions of the presets may not match the version of Babel itself.
For NPM, run
npm install -D babel-loader #babel/core #babel/preset-env webpack
FOR YARN, run
yarn add --dev babel-loader #babel/core #babel/preset-env webpack
Late but might be helpful.
Downgrade the version of #babel-loader to version 7.
It worked for me when i encountered same problem
If you noticed this after installing a package like web3.
Kill the server and try to rebuild hope it helps

Setting up Webpack with Babel for ES6 coding [duplicate]

How to use ES6 in webpack.config ?
Like this repo
https://github.com/kriasoft/react-starter-kit
does ?
For instance:
using this
import webpack from 'webpack';
instead of
var webpack = require('webpack');
It is quite a curiosity rather than a need.
Try naming your config as webpack.config.babel.js. You should have babel-register included in the project. Example at react-router-bootstrap.
Webpack relies on interpret internally to make this work.
As an alternative to what #bebraw suggests, you can create a JavaScript automation script with ES6+ syntax:
// tools/bundle.js
import webpack from 'webpack';
import webpackConfig from './webpack.config.js'; // <-- Contains ES6+
const bundler = webpack(webpackConfig);
bundler.run(...);
And execute it with babel:
$ babel-node tools/bundle
P.S.: Calling webpack via JavaScript API might be a better approach (than by calling it via a command line) when you need to implement more complex build steps. E.g. after server-side bundle is ready, startup Node.js app server, and right after Node.js server is started, launch BrowserSync dev server.
See also:
React Starter Kit (package.json/scripts, tools/bundle.js, tools/webpack.config.js)
React Static Boilerplate (run.js, webpack.config.js, node run)
You might not need Gulp.js
Another approach is to have a npm script like this: "webpack": "babel-node ./node_modules/webpack/bin/webpack", and run it like so: npm run webpack.
This is what worked for me using webpack 4:
In package.json:
"scripts": {
"dev": "cross-env APP_ENV=dev webpack-serve --require #babel/register"
},
"devDependencies": {
"#babel/core": "^7.0.0-rc.1",
"#babel/register": "^7.0.0-rc.1",
"#babel/preset-env": "^7.0.0-rc.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2"
},
"babel": {
"presets": [
["#babel/preset-env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"transform-es2015-modules-commonjs"
]
}
You can clearly see how each dependency is used, so no surprises there.
Note I am using webpack-serve--require, but if you want to use the webpack command instead, replace it with webpack --config-register. In either case, #babel/register is needed to make this work.
And that's it!
yarn dev
And you are able to use es6 in the config!
For webpack-dev-server, use the --config-register option which is the same as with the webpack command
NOTE:
NO need to rename the config file to webpack.config.babel.js (as suggested by the accepted answer). webpack.config.js will work just fine.
I had a problem getting #Juho's solution running with Webpack 2. The Webpack migration docs suggest you to turn of babel module parsing:
It is important to note that you will want to tell Babel to not parse
these module symbols so webpack can use them. You can do this by
setting the following in your .babelrc or babel-loader options.
.babelrc:
{
"presets": [
["es2015", { "modules": false }]
]
}
Sadly, this conflicts with the automatic babel register functionality. Removing
{ "modules": false }
from the babel config got things running again. However, this would result in breaking tree-shaking, so a complete solution would involve overwriting the presets in the loader options:
module: {
rules: [
{
test: /\.js$/,
include: path.resolve('src'),
loader: 'babel-loader',
options: {
babelrc: false,
presets: [['env', {modules: false}]]
}
}
]
}
Edit, 13th Nov 2017; updated webpack config snippet to Webpack 3 (thanks to #x-yuri). Old, Webpack 2 snippet:
{
test: /\.js$/,
exclude: ['node_modules'],
loader: 'babel',
query: {
babelrc: false,
presets: [
['es2015', { modules: false }],
],
},
},
This is really easy, but it wasn't obvious to me from any of the answers, so if anyone else is confused like me:
Just append .babel to the part of your filename before the extension (assuming that you have babel-register installed as a dependency).
Example:
mv webpack.config.js webpack.config.babel.js
Configuration for Babel 7 & Webpack 4
package.json
...
"scripts": {
"start": "webpack-dev-server --env.dev",
"build": "webpack --env.prod",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.0.0",
"#babel/plugin-proposal-class-properties": "^7.0.0",
"#babel/preset-env": "^7.0.0",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"babel-loader": "^8.0.0",
...
"webpack": "^4.17.2",
"webpack-cli": "^3.1.0",
"webpack-config-utils": "^2.3.1",
"webpack-dev-server": "^3.1.8"
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
webpack.config.babel.js
import webpack from 'webpack';
import { resolve } from 'path';
import { getIfUtils, removeEmpty } from 'webpack-config-utils';
export default env => {
const { ifProd, ifNotProd } = getIfUtils(env);
return {
mode: ifProd('production', 'development'),
devtool: ifNotProd('cheap-module-source-map'),
output: {
path: resolve(__dirname, ifProd('prod', 'dev')),
filename: 'bundle.js'
},
For TypeScript: straight from https://webpack.js.org/configuration/configuration-languages/
npm install --save-dev typescript ts-node #types/node #types/webpack
# and, if using webpack-dev-server
npm install --save-dev #types/webpack-dev-server
then proceed to write your, e.g.:
webpack.config.ts
import path from 'path';
import webpack from 'webpack';
const config: webpack.Configuration = {
mode: 'production',
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
}
};
export default config;
Check the link for more details where you can use a plugin to have a separate tsconfig file just for the webpack config if you're not targeting commonjs (which is a req for this to work since it relies on ts-node).
For readers in 2022:
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
Add "type": "module" in package.json
Change the syntax of your webpack.config.js to ESM.
Enjoy.
One more way is to use require argument for node:
node -r babel-register ./node_modules/webpack/bin/webpack
Found this way in electron-react-boilerplate, look at build-main and build-renderer scripts.
Rename webpack.config.js to webpack.config.babel.js.
Then in .babelrc: {"presets": ["es2015"]}
However, if you want to use a different babel config for babel-cli, your .babelrc might look something like this:
{
"env": {
"babel-cli": {
"presets": [["es2015", {"modules": false}]]
},
"production": {
"presets": ["es2015"]
},
"development": {
"presets": ["es2015"]
}
}
}
And in package.json:
{
"scripts": {
"babel": "BABEL_ENV='babel-cli' babel src -d dist/babel --source-maps",
"build-dev": "NODE_ENV='development' webpack -d --progress --profile --colors",
...
},
...
}
It's dumb but the {"modules": false} will break webpack if you don't use different envs.
For more info about .babelrc, check the official docs.
Don't have enough rep to comment, but I wanted to add for any TypeScript users out there a similar solution to #Sandrik above
I have two scripts that I use pointing to webpack configs (JS files) that contain ES6 syntax.
"start-dev": "./node_modules/.bin/ts-node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --config ./webpack/webpack.config.dev.js"
and
"build": "./node_modules/.bin/ts-node ./node_modules/webpack/bin/webpack.js --config webpack/webpack.config.js"
Using Webpack 4 and Babel 7
To setup a webpack configuration file to use ES2015 requires Babel:
Install dev dependencies:
npm i -D webpack \
webpack-cli \
webpack-dev-server \
#babel/core \
#babel/register \
#babel/preset-env
npm i -D html-webpack-plugin
Create a .babelrc file:
{
"presets": ["#babel/preset-env"]
}
Create your webpack config, webpack.config.babel.js:
import { resolve as _resolve } from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const config = {
mode: 'development',
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html'
})
],
resolve: {
modules: [_resolve(__dirname, './src'), 'node_modules']
}
};
export default config;
Create your scripts in package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open"
},
Run npm run build and npm start.
The webpack config is based on a sample project with the following directory structure:
├── README.md
├── package-lock.json
├── package.json
├── src
│   ├── Greeter.js
│   ├── index.html
│   └── index.js
└── webpack.config.babel.js
Sample project: Webpack Configuration Language Using Babel
My Best approach along with npm script is
node -r babel-register ./node_modules/webpack/bin/webpack
and configure rest of scripts as per your requirement for Babel
After tons of the documents...
Just install es2015 preset (not env !!!) and add it to
.babelrc:
{
"presets": [
["es2015", { "modules": false }]
]
}
Rename your webpack.config.js to webpack.config.babel.js
Adding es6 to webpack is a 3 step process
In webpack.config.js add
module:{
rules:[
{
test: /\.js$/,
loader: 'babel-loader'
}
]
}
Create a .babel.rc and add inside it
{
"presets": ["#babel/env", "#babel/react"],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
]
]
}
in package.json add
npm install #babel/core --save-dev
npm install #babel/preset-env --save-dev
npm install #babel/preset-react --save-dev
npm install #babel/plugin-proposal-class-properties --save-dev
npm install babel-loader --save-dev
Edit: Works as of Feb 2021
https://github.com/webpack/webpack-cli/pull/2381
You can't. You have to convert it to CommonJS, either with babel or esm.
https://github.com/webpack/webpack-cli/issues/282
But you can run webpack -r esm #babel/register

Categories

Resources