Babel loader failing - javascript

I have the following example class, containing an example class property arrow function:
class ExampleClass {
example = (params) => {
return params
}
}
Unfortunately this construction isn't yet being well recognized:
ERROR in ./node_modules/example/example.js
Module parse failed: Unexpected token (284:12)
You may need an appropriate loader to handle this file type.
|
| example = (params) => {
| return params
| }
# ./src/example/index.js 8:17-48
# ./src/index.js
# multi (webpack)-dev-server/client?http://localhost:8081 ./src
I have been using the following babel presets and webpack configurations:
Webpack Config
const HtmlWebPackPlugin = require("html-webpack-plugin");
const htmlPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
plugins: [htmlPlugin]
};
.babelrc
{
"presets": ["env", "react", "es2015", "stage-2"]
}
I have no idea what else I need to import here, I'll admit I'm not exactly sure how I would find that out through googling.

I think you can declare method in class with this syntax.
class ExampleClass {
example(params) {
return params
}
}

Related

Webpack Unexpected Token / no loader for filetype

I have a plain JavaScript app that could not be build with WebPack. I removed everything until only those lines remain:
class MyClass {
doStuff = (abc) => {
}
}
The error message I get is the following:
ERROR in ./src/js/mapdata.js 2:12
Module parse failed: Unexpected token (2:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| class MyClass {
> doStuff = (abc) => {
|
| }
My webpack.config looks like this:
const path = require('path');
module.exports = {
entry: './src/js/mapdata.js',
output: {
filename: 'rwmaps.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{ test: /\.json$/, use: 'json-loader' }
]
}
};
I have no clue what the problem is. The JS is working fine if I access it directly from a web page (with ). Any ideas?
You might be missing the babel loader and class properties.
Try adding following dependencies in package.json
"#babel/core": "^7.10.1", "#babel/plugin-proposal-class-properties": "^7.10.1", "#babel/preset-env": "^7.10.1", "babel-loader": "^8.1.0"
Also, create .babelrc and add following code:
{
"plugins": ["#babel/plugin-proposal-class-properties"]
}
Lastly, update webpack.config.js file with following rule:
{ test: /\.m?js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
I hope it helps!

cannot babel transform .marko files with webpack 4

i have a working marko setup for my widget. Im using webpack 4 and babel 7. When i add babel-loader to .marko files, the webpack compiler throws because it couldn't recognize marko's syntax as valid javascript. However the loader should work after the marko transpilation.
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Volumes/Workspace/product-curator-widget/src/index.marko: A class name is required (1:6)
> 1 | class {
| ^
2 | onCreate () {
index.marko
class {
onCreate () {
this.state = {
items: [ {label: 'foo'}, {label: 'bar'} ]
}
const pr = new Promise((resolve) => resolve()) //trying to transpile this arrow function
}
}
<paper>
<chip for (item in state.items) label="${item.label}" value="${item.value}" />
</paper>
webpack.config.js
'use strict'
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports = () => ({
mode: 'development',
devtool: 'cheap-source-map',
entry: [
'core-js',
'./src/index.js'
],
resolve: {
extensions: ['.js', '.marko'],
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/, /\.test\.js$/],
use: ['babel-loader'],
},
{
test: /\.marko$/,
exclude: [/node_modules/, /\.test\.js$/],
use: ['#marko/webpack/loader', 'babel-loader'],
},
{
test: /\.scss$/,
exclude: [/node_modules/],
use: ['style-loader', 'css-loader', 'sass-loader'],
}
],
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: './src/index.html'
}),
new CleanWebpackPlugin()
],
})
babel.config.js
module.exports = function (api) {
api.cache(true)
return {
"plugins": [
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-transform-async-to-generator",
"#babel/plugin-transform-regenerator",
],
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": "10"
}
}
]
]
}
}
Loaders in webpack are evaluated from right to left. In this case, you'll want #marko/webpack/loader to be the first loader to run (put it last in the array), so by the time babel-loader is called, the .marko file has been compiled to JS.
Side note: if you're using Marko components that have been published to npm, you don't want to ignore node_modules. Marko recommends publishing the source .marko files because the compiler produces different output for the server vs the browser. Additionally, the compilation output can be different depending on the version of Marko your app is using.
{
test: /\.marko$/,
use: ['babel-loader', '#marko/webpack/loader'],
},

cannot load html from webpack loader in reactjs

I'm very new to reactjs and webpack. I want to load html file to reactjs via using I use html-loader and webpack, but got this error
Failed to compile.
./src/test_ts.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <!DOCTYPE html>
| <html>
| <body>
This is my webpack config
var path = require("path");
var webpack = require("webpack");
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin("common.js");
module.exports = {
entry: "./src/header.js",
output: {
path: path.resolve(__dirname, "build"),
filename: "app.bundle.js"
},
module: {
loaders: [
{
test: /\.html$/,
loader: "html"
},
{
test: /\.js$/,
loader: "babel-loader",
query: {
presets: ["es2015", "react"]
}
}
]
},
stats: {
colors: true
},
devtool: "source-map"
};
and this is where I want to load
import React from "react";
import { Button } from "reactstrap";
var htmlContent = require("./test_ts.html");
class Header extends React.Component {
render() {
return <div></div>;
}
}
export default Header;
I try to follow many tutorial but can't resolve this, what may I do wrong?
Add the following rule to your webpack.config file:
{
test: /\.(html)$/,
use: {
loader: 'html-loader',
options: {
attrs: [':data-src']
}
}
}
Before that install html-loader using command: npm i -D html-loader :

react-redux-firebase, "You may need an appropriate loader to handle this file type."

I am working on a project that integrates react, redux, and firebase. react-redux-firebase seems to be a convenient tool. However, the code is not being complied successfully. Below is the error, webpack.config.js, .babelrc, and index.js. Thanks for help in advance.
Error message:
ERROR in ./~/react-redux-firebase/src/connect.js
Module parse failed:
/Users/xiqianglin/ucsdflyers/node_modules/react-redux-firebase/src/connect.js
Unexpected token (43:24) You may need an appropriate loader to handle this file type.
| }
|
| static contextTypes = {
| store: PropTypes.object.isRequired
| };
# ./~/react-redux-firebase/src/index.js 1:0-31 # ./src/index.js # multi ./src/index.js
/****And there are other similar errors, all "...appropriate loader..." ***/
webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/src/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: [
'./src/index.js'
],
module: {
loaders: [
{test: /\.js$/,
exclude: /node_modules/,
loader:'babel-loader'}
]
},
resolve: {
extensions: [".js", ".jsx", ".es6"]
},
output: {
filename: "index_bundle.js",
path: __dirname + '/dist'
},
plugins: [HTMLWebpackPluginConfig]
};
.babelrc
{
"presets": ["react", "es2015"]
}
index.js
/*Other Imports...*/
import { firebaseStateReducer } from 'react-redux-firebase'; //This is the line causing error
ReactDOM.render(
<Provider>
<App/>
</Provider>,
documeng.getElementById('app')
)
Duble check that you npm install-ed all your dependencies.
Then if that doesn't work, try this:
npm install babel-preset-es2015
and add the a query for es2015 after your exclude
{
test: /\.js$/,
exclude: /node_modules/,
loader:'babel-loader',
query: {
presets: ['es2015']
}
}
If you need to include a specific node module, try including your source directory and that specific node module folder to be parsed by babel-loader.
So instead of the exclude: /node_modules/, try
include: [
path.resolve(__dirname, "src"),
path.resolve(__dirname, "node_modules/react-redux-firebase")
]

ERROR from UglifyJs: SyntaxError: Unexpected token: operator (>)

I'm getting an error when trying to run my webpack for production.
ERROR in js/main.21dbce548a76ffc14cfb.js from UglifyJs
SyntaxError: Unexpected token: operator (>) [./~/tmi.js/lib/utils.js:3,0][js/main.21dbce548a76ffc14cfb.js:3529,20]
utils.js:3,0 (which is the same as in my minified js) is:
// Return the second value if the first value is undefined..
get: (obj1, obj2) => { return typeof obj1 === "undefined" ? obj2 : obj1; },
So I assume from that the error is thrown because it's reading ES6 but it doesn't understand ES6? (The arrow function)
I don't see what's going wrong here, this is my webpack.config.js
// changed some loader syntax after reading
// https://webpack.js.org/how-to/upgrade-from-webpack-1/
const path = require(`path`);
const webpack = require(`webpack`);
const {UglifyJsPlugin} = webpack.optimize;
const CopyWebpackPlugin = require(`copy-webpack-plugin`);
const ExtractTextWebpackPlugin = require(`extract-text-webpack-plugin`);
const configHtmls = require(`webpack-config-htmls`)();
const extractCSS = new ExtractTextWebpackPlugin(`css/style.css`);
// change for production build on different server path
const publicPath = `/`;
// hard copy assets folder for:
// - srcset images (not loaded through html-loader )
// - json files (through fetch)
// - fonts via WebFontLoader
const copy = new CopyWebpackPlugin([{
from: `./src/assets`,
to: `assets`
}], {
ignore: [ `.DS_Store` ]
});
const config = {
entry: [
`./src/css/style.css`,
`./src/js/script.js`
],
resolve: {
// import files without extension import ... from './Test'
extensions: [`.js`, `.jsx`, `.css`]
},
output: {
path: path.join(__dirname, `server`, `public`),
filename: `js/[name].[hash].js`,
publicPath
},
devtool: `sourcemap`,
module: {
rules: [
{
test: /\.css$/,
loader: extractCSS.extract([
{
loader: `css`,
options: {
importLoaders: 1
}
},
{
loader: `postcss`
}
])
},
{
test: /\.html$/,
loader: `html`,
options: {
attrs: [
`audio:src`,
`img:src`,
`video:src`,
`source:srcset`
] // read src from video, img & audio tag
}
},
{
test: /\.(jsx?)$/,
exclude: /node_modules/,
use: [
{
loader: `babel`
},
{
loader: `eslint`,
options: {
fix: true
}
}
]
},
{
test: /\.(svg|png|jpe?g|gif|webp)$/,
loader: `url`,
options: {
limit: 1000, // inline if < 1 kb
context: `./src`,
name: `[path][name].[ext]`
}
},
{
test: /\.(mp3|mp4)$/,
loader: `file`,
options: {
context: `./src`,
name: `[path][name].[ext]`
}
}
]
},
plugins: [
extractCSS,
copy
]
};
if(process.env.NODE_ENV === `production`){
//image optimizing
config.module.rules.push({
test: /\.(svg|png|jpe?g|gif)$/,
loader: `image-webpack`,
enforce: `pre`
});
config.plugins = [
...config.plugins,
new UglifyJsPlugin({
sourceMap: true, // false returns errors.. -p + plugin conflict
comments: false
})
];
}
config.plugins = [...config.plugins, ...configHtmls.plugins];
module.exports = config;
OP's error is from UglifyJs, as is solved in the accepted answer, some people to this page may get the error from babel, in which case, fix it with: add "presets": ["es2015"] either to the options.presets section of babel-loader, or to .babelrc.
UglifyJs2 has a Harmony branch which accepts ES6 syntax to be minified. At this moment, you need to create a fork of webpack and point webpack to that fork.
I recently answered a couple of similar questions. Please have a look at #38387544 or #39064441 for detailed instructions.
In my case I was using webpack version 1.14
I got help from git ref
steps:
install yarn add uglifyes-webpack-plugin (and removed yarn remove uglifyjs-webpack-plugin)
then install yarn add uglify-js-es6
In webpack.config.js file change new webpack.optimize.UglifyJsPlugin to
new UglifyJsPlugin
then I was able to build. Thanks

Categories

Resources