This question might have been answered somewhere else, but before marking as duplicate, please help me with it. I am referring to the following codepen using react and d3: https://codepen.io/swizec/pen/oYNvpQ
However, I am not able to figure out how can this codepen work with variables declared inside the class without any keywords:
class Colors extends Component {
colors = d3.schemeCategory20;
width = d3.scaleBand()
.domain(d3.range(20));
....
}
When I try to execute this code, I get the following error:
./app/components/D3IndentedTree/Chloreophath.js
Module build failed: SyntaxError: Unexpected token (13:11)
11 | // Draws an entire color scale
12 | class Colors extends Component {
> 13 | colors = d3.schemeCategory20;
| ^
14 | width = d3.scaleBand()
15 | .domain(d3.range(20));
16 |
I am not able to figure out why am I getting this error. I understand that you cant declare variables/properties of class directly inside the class. But how come then the code pen is working?
Thanks in advance!
Update: Adding the webpack.config.js file:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader'] },
{
test: /\.png$/,
loader: "url-loader?limit=100000"
},
{
test: /\.jpg$/,
loader: "file-loader"
},
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader? limit=10000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
}
]
},
plugins: [new HtmlWebpackPlugin({
template: 'app/index.html'
}),
new webpack.ProvidePlugin({
"React": "react",
}),],
devServer: {
historyApiFallback: true
}
};
But how come then the code pen is working?
Because it's using a transpiler (in that case, Babel) that supports that syntax (which is currently a Stage 3 proposal, not a specified feature [yet], but is commonly supported by transpilers used with React code).
You can see that it's transpiling with Babel because it says "(Babel)" next to "JS" in the JS pane's header:
...and if you click the gear icon next to it, you'll see Babel selected as the "Preprocessor".
In this particular case, Babel takes this:
class Colors extends Component {
colors = d3.schemeCategory20;
width = d3.scaleBand()
.domain(d3.range(20));
// ....
}
...and makes it as though it had been written like this:
class Colors extends Component {
constructor() {
this.colors = d3.schemeCategory20;
this.width = d3.scaleBand()
.domain(d3.range(20));
}
// ....
}
...(and then might well turn that into ES5-compliant code, depending on the transpiling settings).
Related
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'],
},
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
}
}
I'm using webpack along with gulp and this is my webpack config:
webpack.config.js
const path = require('path');
var HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
output: {
publicPath: "./dist/",
path: path.join(__dirname, "/js/"),
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["env"]
}
},
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
resolve: {
alias: {
moment: 'moment/src/moment'
}
},
externals: {
jquery: 'jQuery',
$: 'jQuery',
moment: 'moment',
"velocity-animate": 'velocity'
},
plugins: [
new HardSourceWebpackPlugin()
]
};
scripts.js ( This is all that's in this file )
import velocity from 'velocity-animate';
And I get this error
Uncaught ReferenceError: velocity is not defined
Error on this line:
module.exports = velocity;
Am I doing something wrong with the externals configuration?
This works for both moment.js and jQuery, but not for velocity...
I've tried
"velocity-animate": 'velocity'
and
"velocity-animate": 'velocity-animate'
and
"velocity-animate": '"velocity-animate"'
And none of these work. If the first one isn't 'velocity-animate' ( the name of the package ) then Velocity.js gets included in the script anyway. The documentation on this doesn't really explain how to properly configure this
Is it really possible that this use case is so niche that nobody on earth can explain it?
Thanks!
Lead dev of Velocity V2 here.
Doh - we'd missed updating the export of Velocity - I'll get that in later today. We're also in the process of module-ifying it, so you'll be able to import it "normally" within a Webpack project (including tree shaking etc) - that should be done in the next week or so.
Until I push an updated build the name it's exporting as is "Velocity" - note the capital "V" - hopefully later today it'll move over (2.0.2#beta will have the corrected name of "velocity-animate").
I have a bit of an issue here that I can't get to the bottom of.
Here's a snippet from my Graph.js file:
class Graph extends React.Component {
#observable newTodoTitle = "";
s = 40
There error in webpack is as follows:
ERROR in ./src/components/Graph.js
Module build failed: SyntaxError: Unexpected token (13:6)
2018-01-11T14:56:05.221073500Z
11 |
12 |
> 13 | let s = 40
| ^
If I remove the "let", it compiles fine!
I'd prefer to keep the var, let, consts, etc. as I want to copy and paste a lot of JavaScript into this file without these errors.
Here's my .babelrc
{
"presets": [
"react",
"es2015",
"stage-1"
],
"plugins": ["transform-decorators-legacy"]
}
And here's my webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [{
test: /\.jsx?$/,
use: ['babel-loader'],
include: path.join(__dirname, 'src')
}]
}
};
Any ideas?
You are trying to use the class-fields proposal (stage 3 currently) which you will need the Class properties transform plugin of babel to support this.
As you can see in the docs, your syntax is off.
There is no need for any variable declaration key word for class fields.
Example from the docs:
class Counter extends HTMLElement {
x = 0;
clicked() {
this.x++;
window.requestAnimationFrame(this.render.bind(this));
}
constructor() {
super();
this.onclick = this.clicked.bind(this);
}
connectedCallback() { this.render(); }
render() {
this.textContent = this.x.toString();
}
}
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