Webpack/Babel es2015 error: Uncaught SyntaxError: Unexpected token import - javascript

after looking at the possible solutions for the issue i had, couldn't find a way to solve this error:
Uncaught SyntaxError: Unexpected token import
Im stuck at this point and cant seem to solve it (feel a bit restless when trying to learn and work).
P.S. I appreciate your time and help. Im relatively a new developer, pardon me if i have asked anything stupid. thanks
For your expert review, here's the relevant files that im working with:
package.json
{
"name": "",
"version": "1.0.0",
"dependencies": {
"browser-sync": "^2.18.6",
"browsersync": "0.0.1-security",
"jquery": "^3.1.1",
"jquery-smooth-scroll": "^2.1.2",
"lazysizes": "^3.0.0-rc3",
"normalize.css": "^5.0.0",
"picturefill": "^3.0.2",
"waypoints": "^4.0.1"
},
"devDependencies": {
"autoprefixer": "^6.7.0",
"babel-core": "^6.22.1",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.22.0",
"del": "^2.2.2",
"gulp": "^3.9.1",
"gulp-cssnano": "^2.1.2",
"gulp-imagemin": "^3.1.1",
"gulp-modernizr": "^1.0.0-alpha",
"gulp-postcss": "^6.3.0",
"gulp-rename": "^1.2.2",
"gulp-rev": "^7.1.2",
"gulp-svg-sprite": "^1.3.1",
"gulp-svg2png": "^0.3.0",
"gulp-uglify": "^2.0.1",
"gulp-watch": "^4.3.11",
"postcss-hexrgba": "^0.2.1",
"postcss-import": "^9.1.0",
"postcss-mixins": "^5.4.1",
"postcss-nested": "^1.0.0",
"postcss-simple-vars": "^3.0.0",
"webpack": "^2.2.1"
}
}
webpack.config.js
module.exports = {
entry: {
app: "./app/assets/scripts/App.js"
},
output: {
path: "./app/temp/scripts",
filename: "App.js"
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['es2015']
},
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
App.js
import MobileMenu from './modules/MobileMenu';
var mobileMenu = new MobileMenu();
MobileMenu.js
class MobileMenu {
constructor() {
alert("testing 123")
}
}
export default MobileMenu;
scripts.js
var gulp = require('gulp'),
webpack = require('webpack');
gulp.task('scripts', ['modernizr'], function(callback) {
webpack(require('../../webpack.config.js'), function(err, stats) {
if (err) {
console.log(err.toString());
}
console.log(stats.toString());
callback();
});
});

Solution
As it seems that it doesnt really matter which version of the babel core, babel-loader we actually use. Also .babelrc file was not required for me. What worked for me was to include the bundled file in my HTML which was generated at temp/scripts/App.js, instead of including the original source at assets/scripts/App.js. Thats it ! cheers
Thanks to #MichaelJungo

Related

Module parse failed: Unexpected token (238:16) You may need an appropriate loader to handle this file type

I am trying to use ArcballControls.js controls inside my vue js application. This Class has functions which uses arrow syntax, and every other class in controls does not use arrow syntax. This is the only difference i could understand between other files.
Below is the ArcballControls.js provided by three js
https://github.com/mrdoob/three.js/blob/dev/examples/jsm/controls/ArcballControls.js
This below is the whole jsm/controls from three.js
https://github.com/mrdoob/three.js/tree/dev/examples/jsm/controls
When i try to use this controls inside my application i am getting this error.
error in ./node_modules/three/examples/jsm/controls/ArcballControls.js
Module parse failed: Unexpected token (238:16)
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
| //listeners
|
> onWindowResize = () => {
|
| const scale = ( this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z ) / 3;
# ./node_modules/cache-loader/dist/cjs.js??ref--13-0!
./node_modules/#vue/cli-plugin-babel/node_modules/babel-loader/lib!
./node_modules/cache-loader/dist/cjs.js??ref--1-0!
./node_modules/vue-loader/lib??vue-loader-options!
./src/components/Sidebar/ThreeDCanvas.vue?vue&type=script&lang=js
This is my package.json file
"dependencies": {
"#babel/plugin-transform-arrow-functions": "^7.16.7",
"three": "^0.133.0",
"vue": "^2.6.11",
"vue-style-loader": "^4.1.2",
"vuetify": "^2.6.3",
"vuex": "^3.1.2"
},
"devDependencies": {
"#babel/core": "^7.17.8",
"#babel/preset-env": "^7.16.11",
"#mdi/font": "^6.5.95",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "^3.12.1",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.2.31",
"#vue/eslint-config-prettier": "^4.0.1",
"babel-core": "^6.26.3",
"babel-eslint": "^10.1.0",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"css-loader": "^3.5.3",
"less-loader": "^5.0.0",
"node-sass": "^7.0.1",
"prettier-eslint": "^13.0.0",
"sass": "^1.49.7",
"sass-loader": "^7.3.1",
"vue-svg-loader": "^0.12.0",
"vue-template-compiler": "^2.6.11",
"webpack": "^4.46.0"
},
Inside config/index.js, in module property, this is how i set up the babel loader, i am not sure if its the right way to do it.
module: {
rules: [
{
test: /\.s(c|a)ss$/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'sass-loader',
// Requires sass-loader#^7.0.0
options: {
implementation: require('sass'),
indentedSyntax: true, // optional
},
},
],
},
{
test: /\.js$/,
exclude: /node_modules(?!\/three)/,
use: [
{
loader: 'babel-loader',
options: {
presets: [['#babel/preset-env', { targets: 'defaults' }]],
},
},
],
},
],
},
This is my component where i initialize the threed scene
<script type="module">
import * as Three from 'three'
import ThreeScene from '#/components/Scene/ThreeScene.js'
import Renderer from '#/components/Scene/Renderer.js'
import Camera from '#/components/Scene/Camera.js'
import HLight from '#/components/Scene/HLight.js'
import DLight from '#/components/Scene/DLight.js'
//import is here
import { ArcballControls } from 'three/examples/jsm/controls/ArcballControls.js'
import ObjectLoader from '#/components/Scene/ObjectLoader.js'
import CubeLoader from '#/components/Scene/CubeLoader.js'
export default {
name: 'ThreeDCanvas',
data() {
return {}
},
methods: {
init() {
this.scene = new ThreeScene()
this.camera = new Camera()
this.renderer = new Renderer({ antialias: true })
this.objectLoader = new ObjectLoader()
this.controls = new ArcballControls(
this.camera,
this.renderer.domElement,
this.scene
)
Could some one help me to find what i am doing wrong here ?
Inside the file config/index.js on module added babel loader.
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader']
},
in package.json removed unnecessary dependencies and downgraded some.
Node version i am using is 14.17.4 and because of that, node-sass had to downgrade to 4.14.1,
after the issue with loader for threejs was fixed, i had issues with
sass loader.
"node-sass": "^4.14.1",
"prettier-eslint": "^13.0.0",
"sass": "^1.49.7",
"sass-loader": "^7.3.1",
"#babel/core": "^7.12.16",
"#babel/eslint-parser": "^7.12.16",
i removed babel-loader and babel-preset-es2015 from package.json.
This is my babel-config.js
module.exports = {
presets: ['#vue/cli-plugin-babel/preset'],
}
When i made these changes i am able to access the arcballcontrol from threejs.

Callback of onMounted is not being triggered in vue 3 plugin that bundled by webpack

Forgive me for getting long content to explain my problem.
I made a simple npm vue3-helloword-webpack plugin. This plugin consoles the simple text from inside the onMounted method.
If I bundle this helloworld plugin using vue-cli tool, the callback of onMounted from plugin would be triggered. But same does not happen while bundling by webpack.
I think the problem is occurred because of currenIntance(I guess it’s a vue instance) is null as shown in below image.
Content: when the plugin is bundled by webpack
Webpack.config.babel.js
const TerserPlugin = require("terser-webpack-plugin")
const libraryNamePlugin = 'vue3-helloworld-webpack';
const appConfig = {
entry: {
'vue3-helloworld-webpack': __dirname + '/src/index.js',
'vue3-helloworld-webpack.min': __dirname + '/src/index.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: '[name].js',
library: libraryNamePlugin,
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /(\.jsx|\.js)$/,
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/
},
{
test: /(\.jsx|\.js)$/,
loader: 'eslint-loader',
exclude: /node_modules/
}
]
},
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
include: 'vue3-helloworld-webpack.min.js',
}),
],
},
};
module.exports = [appConfig];
package.json
....
"main": "dist/vue3-helloworld-webpack.js",
"scripts": {
"build": "webpack --config webpack.config.babel.js"
},
"dependencies": {
"core-js": "^3.6.5"
},
"devDependencies": {
"#babel/core": "^7.14.3",
"#babel/preset-env": "^7.14.4",
"#babel/register": "^7.13.16",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"babel-plugin-add-module-exports": "^1.0.4",
"babel-preset-es2015": "^6.24.1",
"chai": "^4.3.4",
"eslint": "^7.27.0",
"eslint-loader": "^4.0.2",
"lodash": "^4.17.21",
"mocha": "^8.4.0",
"terser-webpack-plugin": "^5.1.3",
"vue": "^3.0.0",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2",
"yards": "^0.1.4"
}
....
vue3-helloworld-webpack.js
import {onMounted, h} from 'vue'
const config = { msg: String }
export default {
name: 'vue3-helloworld-webpack',
props : config,
setup(props) {
console.log("setup() is invoked")
console.log(props.msg);
onMounted(function () {
console.log("Hooray!!! Onmounted() is triggered")
});
},
render() {
return h('div', {
id: 'helloworld-1'
});
}
}
src/index.js
import vue3helloworldwebpack from './vue3-helloworld-vuewebpack';
const install = (app) => {
app.component(vue3helloworldwebpack.name, vue3helloworldwebpack);
};
export default install;
Result: when the plugin is used by other very simple vue app
Content when the plugin bundled by Vue-cli
package.json
....
"main": "dist/vue3-helloworld-vuecli.umd.js",
"scripts": {
"build": "vue-cli-service build --formats umd --target lib ./src/index.js"
},
"dependencies": {
"core-js": "^3.6.5"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^4.5.6",
"#vue/cli-plugin-eslint": "^4.5.6",
"#vue/cli-plugin-unit-jest": "^4.5.6",
"#vue/cli-service": "^4.5.6",
"#vue/compiler-sfc": "^3.0.0-rc.10",
"#vue/test-utils": "^2.0.0-beta.5",
"babel-eslint": "^10.1.0",
"babel-jest": "^26.3.0",
"eslint": "^7.9.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-vue": "^7.0.0-0",
"husky": "^6.0.0",
"prettier": "^2.1.1",
"typescript": "^4.0.2",
"vue": "^3.0.0",
"vue-jest": "^5.0.0-alpha.4"
}
....
Other codes are similar to webpack version except name and webpack config file.
Result
The other simple vue3 app which is using the created plugin(vue3-helloworld-webpack)
Main.js
import { createApp } from 'vue'
import App from './App.vue'
import Vue3HelloworldWebpack from 'vue3-helloworld-webpack'
createApp(App).use(Vue3HelloworldWebpack).mount('#app')
App.vue
<template> <vue3-helloworld-webpack msg="Welcome!!!!" /></template>
We can get created plugins: webpack and vue-cli versions on GitHub.
My question
Vue cli version does work. One interesting thing, the same webpack file configuration is working for vue2 plugin also.
But it does not work for vue 3 plugin, How can I do this without using vue-cli but using webpack version ?

Cant create SharedWorker with worker-loader

Trying to create SharedWorker with worker-loader
It doesnt create it, just Worker is created. Seems like it ignores options.
Usage in parent code
import SharedWorker from "worker-loader!./workers/get-nth-fibonacci-number.shared-worker.js";
import "./styles/style.scss";
const btn = document.getElementById("calc-btn");
const input = document.getElementById("nth-input");
const result = document.getElementById("result-el");
const worker = new SharedWorker();
console.log("worker", worker);
worker.port.addEventListener("message", (e) => {
result.innerHTML = e.data;
});
worker.port.addEventListener("error", (e) => {
result.innerHTML = `message: ${e.message}; filename: ${e.filename}; line: ${e.lineno}`;
console.error(e);
});
//...
worker code
import { getNthFobonacciNumber } from "../helpers/get-nth-fibonacci-number.js";
console.log("hello from worker");
self.addEventListener("connect", function (e) {
const port = e.ports[0];
console.log("port", port);
port.addEventListener("message", function (e) {
const num = e.data;
if (Number.isInteger(parseInt(num))) {
const result = getNthFobonacciNumber(num);
port.postMessage({ result, port });
} else {
throw new Error("Is not a number");
}
});
port.start();
});
webpack rule
{
test: /\.shared-worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
worker: "SharedWorker",
},
},
But in console it is shown as Worker class. What is wrong with it?
dependencies
"#babel/core": "^7.7.7",
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.7.7",
"babel-loader": "^8.0.6",
"brotli-webpack-plugin": "^1.1.0",
"clean-webpack-plugin": "^3.0.0",
"compression-webpack-plugin": "^3.0.1",
"css-loader": "^3.4.1",
"cssnano": "^4.1.0",
"file-loader": "^5.0.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"postcss-loader": "^3.0.0",
"postcss-preset-env": "^6.7.0",
"purgecss-webpack-plugin": "^1.6.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.1.2",
"terser-webpack-plugin": "^2.3.1",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1",
"worker-loader": "^3.0.5"
This thing asks me to add some more details: "It looks like your post is mostly code; please add some more details." This is just a stub text. I'm sorry.
Solved by using alternative plugin https://github.com/GoogleChromeLabs/worker-plugin
with worker-loader you can, create the file with the extension .sharedworker.js and in webpack rules you do this
{
test: /\.sharedworker\.js$/,
use: [
{
loader: 'worker-loader',
options: {
filename: '[name].[hash:8].js',
inline: 'fallback',
worker: {
type: 'SharedWorker',
options: {
credentials: 'omit',
name: 'mySharedWorker' // for debbuging
}
}
}
},
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
]
}
you can delete worker-loader! in your import code.
worker-loader! will change options to {}
just use webpack config only.
I have same question, and sovled it

Webpack 2: Cannot read property 'Base64' of undefined

I'm new to Webpack. My React config works, but when I try to import postcssJs from 'postcss-js' the browser throws an Uncaught TypeError: Cannot read property 'Base64' of undefined in the bundle on var _Base64 = global.Base64;.
Here is my webpack config:
module.exports = {
entry: './demo/js/components/App.js',
output: {
path: __dirname + '/demo/js',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
query: {
presets: [
'es2015',
'stage-0',
'react'
],
plugins: [
'transform-react-stateless-component-name'
]
}
}
]
},
node: {
fs: 'empty'
},
watch: true
}
Here is the React file I'm having problems with:
import React from 'react'
import postcssJs from 'postcss-js' // When I comment out this line, everything works fine.
export default ({greeting}) => <h3>{greeting}</h3>
I'm sure I'm just missing some basic Webpack paradigm about using some sort of loader or something, but I can't figure it out.
I'd really appreciate any help as this has been blocking me for several hours now...
Here are my dependencies:
"dependencies": {
"chalk": "^1.1.3",
"postcss": "^5.2.5",
"postcss-value-parser": "^3.3.0"
},
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-loader": "^6.2.5",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-transform-flow-strip-types": "^6.18.0",
"babel-plugin-transform-react-stateless-component-name": "^1.0.1",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-0": "^6.16.0",
"browser-sync": "^2.17.5",
"imports-loader": "^0.6.5",
"lodash": "^4.16.4",
"npm-run-all": "^3.1.1",
"postcss-js": "^0.1.3",
"react": "^15.4.0-rc.4",
"react-dom": "^15.4.0-rc.4",
"stylus": "^0.54.5",
"webpack": "^2.1.0-beta.25"
}
It works without Babel, but I need Babel...

Why is "-" (dash) giving "Unexpected token error" on Babelify with Gulp?

I am setting up (or actually modifying existing) project with Browserify and Babelify. For some reason I can't configure my gulpfile properly. The project itself is a React project, if it matters.
I got rid of most of the problems, but now I am getting "Unexpected token" error on Browserify. It is caused by React components or html elements with attribute names which have a dash, ie. the following:
<button type="button" data-toggle="collapse">
My Browserify task:
gulp.task('browserify', function() {
browserify('./src/js/main.js')
.transform(babelify.configure({
presets: ["react", "es2015"]
}))
.bundle()
.on('error', function(err){
process.stdout.write('' + err + '\n');
notifier.notify({
title: 'Error',
message: err,
sound: true,
wait: true
}, function (err, response) {
});
})
.pipe(source('main.js'))
.pipe(gulp.dest('dist/js'))
.pipe(connect.reload());
});
Package.json:
{
"name": "srcd-mockup",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"dependencies": {
"babel-preset-es2015": "^6.0.12",
"bootstrap-sass": "^3.3.5",
"browserify": "^11.2.0",
"flux": "^2.1.1",
"font-awesome": "^4.4.0",
"gulp": "^3.9.0",
"gulp-concat": "^2.6.0",
"jquery": "^2.1.4",
"lodash": "^3.10.1",
"node-notifier": "^4.3.1",
"react": "^0.14.1",
"react-dom": "^0.14.1",
"react-redux": "^4.0.0",
"react-router-component": "^0.27.2",
"reactify": "^1.1.1",
"redux": "^3.0.4",
"redux-logger": "^2.0.4",
"updeep": "^0.10.1",
"vinyl-source-stream": "^1.1.0"
},
"devDependencies": {
"babel-preset-react": "^6.0.12",
"babelify": "^7.0.2",
"gulp-connect": "^2.2.0",
"gulp-notify": "^2.2.0",
"gulp-sass": "^2.0.4",
"gulp-uglify": "^1.4.1",
"redux-devtools": "^2.1.5"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
What I tried before:
The weird thing here is that previously I had similar project with similar dependencies and config, and it worked fine.
Then I tried to set up the new one, and first I got Unexpected token error on this line on my main.js (initial render of React):
ReactDOM.render(<App />, document.getElementById('main'));
The error was caused by "(". Then there was no presets on Babelify.
If I only have "react" on presets, I get "ParseError: 'import' and 'export' may appear only with 'sourceType: module'", because of, well importing.
Questions:
Is this related to Babelify or can it be caused by other module or dependency?
Is this related to Babel 6?
Why is dash causing the error?
How should I set this up?
There appears to be a bug as of Babel version 6.0.12 which is rendering data-* tags as object keys without quoting them, resulting in invalid JS syntax.
You can use a pre-v6 version of Babel, or else wait for someone to submit a fix.
UPDATE:
A fix for this just got checked into the repo, so this will be fixed in the next release.

Categories