SyntaxError: Unexpected token import error - javascript

I am getting "Unexpected token import" when trying to run my react app
error that I am getting
User:my-version username$ node build
User:my-version username$ node app.js
/Users/Hindreen/Documents/workspace/apps/test/app.js:1
(function (exports, require, module, __filename, __dirname) { import React
from 'react';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:588:28)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
User:test username$
app.js
import React from 'react';
import ReactDOM from 'react-dom';
class Application extends React.Component {
render() {
return (
<div className="container">
<h1>Hello From React</h1>
</div>
);
}
}
build.js
var fs = require("fs");
var browserify = require("browserify");
var babelify = require("babelify");
browserify({ debug: true })
.transform(babelify)
.require("./app.js", { entry: true })
.bundle()
.on("error", function (err) { console.log("Error: " + err.message); })
.pipe(fs.createWriteStream("bundle.js"));
.babelrc
{
"presets": ["env", "react"],
"plugins": ["transform-es2015-modules-amd"]
}
package.json devDependencies
{
"devDependencies":{
"babel-plugin-transform-es2015-modules-amd": "^6.24.1",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.24.1",
"babelify": "^7.3.0",
"browserify": "^13.3.0",
"react": "^15.0.2",
"react-dom": "^15.0.2"
}
}
I appreciate any help, Thanks in advance and please let me know if my question is not clear.

const React = require('react'),
ReactDOM = require('react-dom');
if you write in ES6-syntax => install and use babel

-> User:my-version username$ node app.js
Unless you want to run your code server side, this is not the appropriate way to bootstrapping your 'build' code.
Please refer to the following which mimics your setup: https://repl.it/repls/RemoteJovialSignature
(it doesn't actually run, it's only for viewing purposes).
Steps to run locally:
node build - builds the bundle.js
Open index.html in your browser

I just solved saving my script file text.js back to UTF from Unicode. Probably the single-quote (') in Unicode was not recognized.
It was failing in line
var mysql = require('mysql');

Related

Both Require and import not working javascript

I am trying to create a cli tool to make a todo list. For some reason I can't figure out I'm unable to use either require or import when trying to import the Chalk package for highlighting terminal outputs
here is what I have for my index.js file
#! /usr/bin/env node
const { program } = require("commander");
const list = require("./commands/list.js");
program.command("list").description("List all the TODO tasks").action(list);
program.parse();
Here is my list.js file
#! /usr/bin/env node
const conf = new (require("conf"))();
const chalk = require("chalk");
function list() {
const todoList = conf.get("todo-list");
if (todoList && todoList.length) {
console.log(
chalk.blue.bold(
"Tasks in green are done. Tasks in yellow are still not done."
)
);
todoList.forEach((task, index) => {
if (task.done) {
console.log(chalk.greenBright(`${index}. ${task.text}`));
} else {
console.log(chalk.yellowBright(`${index}. ${task.text}`));
}
});
} else {
console.log(chalk.red.bold("You don't have any tasks yet."));
}
}
module.exports = list;
and my package.json file
{
"name": "near-clear-state",
"version": "1.0.0",
"description": "Tool to let NEAR users clear the state of their account ",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "commonjs",
"author": "Dorian",
"license": "ISC",
"dependencies": {
"chalk": "^5.0.0",
"commander": "^8.3.0",
"conf": "^10.1.1",
"near-api-js": "^0.44.2"
},
"bin": {
"near-clear-state": "./index.js"
}
}
when I try running anything from this cli tool I'm making I get this error if I use require
➜ near-clear-state near-clear-state --help
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4
const chalk = require("chalk");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/node_modules/chalk/source/index.js from /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js not supported.
Instead change the require of index.js in /Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:4:15)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14) {
code: 'ERR_REQUIRE_ESM'
}
Or this error when i use import
/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/commands/list.js:3
import { Chalk } from "chalk";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1026:15)
at Module._compile (node:internal/modules/cjs/loader:1061:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/doriankinoocrutcher/Documents/NEAR/Developer/near-clear-state/index.js:3:14)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
Node.js v17.4.0
Please help me
Use the import syntax, and add "type": "module" into your package.json to allow for ES6 imports.

Webpack Build SyntaxError: Unexpected token )

Note: I read through the other similar questions (here and others), but they are all about earlier versions of webpack and babel and do not solve the following issue.
This is serving just fine, but when I run npm run build I'm getting the following error. How do I solve this? (And how do I get better errors than this?, the log is just as bad).
> react_01#1.0.0 build /Users/monkeydo/Documents/code/__tests/react_01
> webpack --mode production
/Users/monkeydo/Documents/code/__tests/react_01/node_modules/webpack-cli/bin/cli.js:41
)} manually.`,
^
SyntaxError: Unexpected token )
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at runCli (/Users/monkeydo/Documents/code/__tests/react_01/node_modules/webpack/bin/webpack.js:69:2)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react_01#1.0.0 build: `webpack --mode production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react_01#1.0.0 build script.
My webpack file looks like this:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
//entry: ['#babel/polyfill', './src/index.js'],
entry: './src/index.js',
// Where files should be sent once they are bundled
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.bundle.js'
},
// webpack 5 comes with devServer which loads in development mode
devServer: {
port: 3000,
watchContentBase: true
},
// Rules of how webpack will take our files, complie & bundle them for the browser
module: {
rules: [
{
test: /\.(js|jsx)$/,
// test: /\.jsx?/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader',
query:
{
presets:['react', 'preset-env']
}
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' }), new MiniCssExtractPlugin()]
}
My package json looks like this:
{
"name": "react_01",
"version": "1.0.0",
"description": "",
"main": "index.jsx",
"scripts": {
"serve": "webpack serve --mode development",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/preset-env": "^7.14.7",
"#babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"css-loader": "^6.0.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.1.0",
"style-loader": "^3.1.0",
"webpack": "^5.45.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
My babelrc file looks like this:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
My index.js file looks like this:
import React from "react"
import ReactDom from "react-dom"
import App from "./components/app"
import "./style.css"
ReactDom.render(<App />, document.getElementById('app'))
My app.js file looks like this:
import React from "react"
function App() {
return (<div>
<h2>Welcome to My new React App</h2>
<h3>Date : {new Date().toDateString()}</h3>
</div>)
}
export default App
*** Edit: not sure what I was thinking... I totally forgot to add the webpack code before :o ! I guess that was a dyslexic senior moment. It's added now.
Just remove the styles import
import "./style.css"
Webpack speaks JavaScript, not css, if you want it to learn it you need to create a webpack config file and use the proper loader to handle css

JavaScript problem with import, weird error

I have some code using library:
import { generateKeyPair } from 'jose/util/generate_key_pair'
async function funkcja () {
const {publicKey, privateKey} = await generateKeyPair('PS256')
console.log(publicKey)
console.log(privateKey)
}
funkcja()
and while trying to node it i get following error:
ubuntu#ubuntu-VirtualBox:~/Desktop/js$ node hello.js
/home/ubuntu/Desktop/js/hello.js:1
import { generateKeyPair } from 'jose/util/generate_key_pair'
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
I have no idea why this is happening, my friend is using exact same library and same code and on his computer it's working fine. (path to the library is correct) The only differennce is that he has node v12 and i have node v10.
Try this one
const { generateKeyPair } = require('jose/util/generate_key_pair');
Don't forget to use module.exports in generate_key_pair js file
How i read it in Update on ES6 Modules in Node.js the import of variables via curly brackets seems to be not supported in node.js.
it will simply not be possible to use the syntax:
import {foo, bar} from 'foobar';
But this would be possible:
import foobar from 'foobar';
console.log(foobar.foo(), foobar.bar());
So if generateKeyPair is a variable or function from 'jose/util/generate_key_pair' it should be:
import generate_key_pair from 'jose/util/generate_key_pair'
async function funkcja () {
const {publicKey, privateKey} = await generate_key_pair.generateKeyPair('PS256')
console.log(publicKey)
console.log(privateKey)
}
funkcja()

How to use ospec with mithril javascript

I'm trying to use o.spec to test mycomponent but failed.
The error message of "dart test" is:
tests/MyComponent.js:1
(function (exports, require, module, __filename, __dirname) { import MyComponent from "./src/mycomponent"
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Glob.<anonymous> (node_modules/mithril/ospec/bin/ospec:37:37)
error Command failed with exit code 1.
setup by npm or yarn:
yarn add mithril#next webpack webpack-cli
edit package.json:
{
...
"name": "my-project",
"scripts": {
"start": "webpack src/index.js --output bin/app.js -d --watch",
"build": "webpack src/index.js --output bin/app.js -p",
"test": "ospec"
}
}
index.html:
<!DOCTYPE html>
<body>
<script src="bin/app.js"></script>
</body>
src/mycomponent.js:
//var m = require("mithril")
import m from "mithril"
//module.exports = {
export default {
view: function(vnode) {
return m("div",
m("p", "Hello World")
)
}
}
src/index.js:
import m from "mithril"
import MyComponent from "./mycomponent"
//var m = require("mithril")
//var MyComponent = require("./mycomponent")
m.mount(document.body, MyComponent)
tests/MyComponent.js
import MyComponent from "./src/mycomponent"
//var MyComponent = require("./src/mycomponent")
o.spec("MyComponent", function() {
o("returns a div", function() {
var vnode = MyComponent.view()
o(vnode.tag).equals("div")
o(vnode.children.length).equals(1)
o(vnode.children[0].tag).equals("p")
o(vnode.children[0].children).equals("Hello world")
})
})
You need to mock the environment using
global.window = require("mithril/test-utils/browserMock.js")();
global.document = window.document;
in your tests.
Check more at https://mithril.js.org/testing.html

import unexpected reserved word javascript (using system.js, sammy.js and babel as transpiler ecmascript 6)

I am a newbie in JS and I have some troubles running the test server (like: node app.js ..or iojs app.js) with the new ECMA6 syntax (using import and export)... here is the sample code I am using trying to achive that and the error the server is returning :
<script>
System.config({
baseURL:"/",
transpiler: "babel",
babelOptions: {
"optional": [
"runtime"
]
},
paths: {
"npm:*": "node_modules/*",
"bower:*": "bower_components/*"
},
map: {
"babel": "npm:babel-core/browser.js",
"sammy": "bower:sammy/lib/sammy.js",
"jquery":"bower:jquery/dist/jquery.js",
"handlebars": "bower:handlebars/handlebars.js"
}
});
</script>
<script type="text/javascript">
System.import('app.js')
.then(function(module) {
module.init('#content');
});
</script>
and in app.js the following simple code :
import $ from 'jquery';
import sammy from 'sammy';
import homeController from './controllers/homeController.js';
export function init (element) {
var sammyApp = Sammy(element, function() {
this.get('#/', homeController.load);
});
sammyApp.run('#/');
}
then o recive the following error screen when trying to execute the test server:
D:\TELERIK\JavaScript-Apps\exam-prepar-evlogi>iojs app.js
D:\TELERIK\JavaScript-Apps\exam-prepar-evlogi\app.js:1
(function (exports, require, module, __filename, __dirname) { import $ from 'j
^^^^^^
SyntaxError: Unexpected reserved word
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:448:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:471:10)
at startup (node.js:117:18)
at node.js:948:3
Any advice on where my fault is would be great.. Thank you all in advance

Categories