Reactjs: Unexpected Token - node.js

I'm trying to follow the tutorial here: https://facebook.github.io/react/docs/getting-started.html
Simply trying to build the following, either within Sublime Text 3, or webpack:
// ReactTest.js
var React = require('react');
var ReactDOM = require('react-dom');
console.log("Hello");
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
I've installed Sublime Text 3, as well as the following packages via Package Control, Install:
Babel for syntax highlighting
Sublime Linter (3) for error checking
Sublime Linter-contrib-eslint (an interface for eslint)
I have already installed node via homebrew:
brew install node
Used NPM to install the following:
npm install webpack -g
npm install --save react react-dom babel-preset-react babel-preset-es2015
npp install jsxhint -g
npm install -g jshint
From what I understand, this should be everything I need to run either of the two options:
Use Sublime Text 3's build: I added a new 'build system' for Sublime Text by Tools -> Build System -> New Build System and created the file:
{ "cmd" : ["/usr/local/bin/node", "$file"], "selector":"source.js" }
which is saved to me/Library/ApplicationSupport/SublimeText3/Packages/user/node.sublime.build on my osx.
I run Tools -> Build to build which results in:
/Users/me/Desktop/Test/ReactTest.js:8
<h1>Hello, world!</h1>,
^
SyntaxError: Unexpected token <
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
[Finished in 0.1s with exit code 1]
[cmd: ['/usr/local/bin/node', '/Users/me/Desktop/Test/ReactTest.js']]
[dir: /Users/me/Desktop/Test]
[path: /usr/bin:/bin:/usr/sbin:/sbin]
Also tried to do the same thing using webpack with the following command:
webpack ReactTest.js Bundle.js
Which results in:
ERROR in ./ReactTest.js
Module parse failed: /Users/me/Desktop/Test/ReactTest.js Line 8: Unexpected token <
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
| <h1>Hello, world!</h1>,
| document.getElementById('example')
| );
Can anyone tell me what I'm doing wrong?
EDIT: Completely new to all of these technologies. Here's a screenshot of my project in Sublime Text.
EDIT 2: The .babelrc file, which I've copied from the web:
{
"plugins": ["transform-react-jsx"],
"ignore": [
"foo.js",
"bar/**/*.js"
]
}

If you are using JSX in your code, you have to transpile to js using loaders in webpack.
module.exports = {
entry: 'ReactTest.js',
output: {
path: path.join(__dirname, './dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /.js$/,
exclude : /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
}
]
}
};
Make sure you configured .babelrc in root path if you are using ES2015 syntax
copy and use the below webpack config in your webpack.config.js
run webpack in root folder
include bundle.js in your index.html.
Let me know if you face any difficulties

Related

Vite can't build .graphql files from node_modules

I'm working on move my build from vue-cli to vite.
So I got problem with the package that contain part of my app code (package placed in node_modules). In this package I have *.vue and *.graphql files, like source code without any compilation. I import that files and with vue-cli it works well, but with vite i get error:
Error: Build failed with 17 errors:
ERROR: No loader is configured for ".graphql" files: node_modules/<path-to-file>.graphql
...
at failureErrorWithLog (node_modules/esbuild/lib/main.js:1624:15)
at node_modules/esbuild/lib/main.js:1266:28
at runOnEndCallbacks (node_modules/esbuild/lib/main.js:1046:63)
at buildResponseToResult (node_modules/esbuild/lib/main.js:1264:7)
at node_modules/esbuild/lib/main.js:1377:14
at node_modules/esbuild/lib/main.js:678:9
at handleIncomingPacket (node_modules/esbuild/lib/main.js:775:9)
at Socket.readFromStdout (node_modules/esbuild/lib/main.js:644:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
Although, for my local .graphql files it works without any errors.
And maybe important thing - when I try to use yarn link for this package, it start to works! It's great but I can't use yarn link any time. It looks like bug of vite or maybe of the plugin #rollup/plugin-graphql.
node v16.17.0 (npm v8.15.0)
vite.config.js:
import { defineConfig } from 'vite';
import Vue from '#vitejs/plugin-vue2';
import Graphql from '#rollup/plugin-graphql';
export default defineConfig({
server: {
port: 8011,
},
plugins: [
Graphql(),
Vue(),
],
});
vite: 3.0.9
#rollup/plugin-graphql: 1.1.0
#vitejs/plugin-vue2: 1.1.2

Electron cannot open shared object file from node_modules folder

On electron, the node module vosk needs to access some shared objects located in node_modules/vosk/lib/.
The issue I am having right now is that, when I do require('vosk') in my main.js and try to execute my AppImage file, I get:
A JavaScript error occurred in the main process
Uncaught Exception:
Error: Dynamic Linking Error: /tmp/.mount_CantooClaxGf/resources/app.asar/node_modules/vosk/lib/linux-x86_64/libvosk.so: Cannot open the shared object: It's not a folder
at new DynamicLibrary (/tmp/.mount_CantooClaxGf/resources/app.asar/node_modules/ffi-napi/lib/dynamic_library.js:75:11)
at Object.Library (/tmp/.mount_CantooClaxGf/resources/app.asar/node_modules/ffi-napi/lib/library.js:47:10)
at Object.<anonymous> (/tmp/.mount_CantooClaxGf/resources/app.asar/node_modules/vosk/index.js:24:21)
at Module._compile (internal/modules/cjs/loader.js:1145:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1166:10)
at Module.load (internal/modules/cjs/loader.js:981:32)
at Module._load (internal/modules/cjs/loader.js:881:14)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (internal/modules/cjs/loader.js:1023:19)
at require (internal/modules/cjs/helpers.js:77:18)
I tried to add vosk to the files in the build:
"build": {
"files": [
"dist/**/*",
"src/assets/icons/*",
"electron.js",
"package.json",
"assets/models/*",
"node_modules/vosk/lib/*"
],
I can now see the files in the app.asar.unpacked/node_modules/vosk/lib/ folder, but when executing the app, I'm still having the same error.
I found this answer mentioning a hack, but it didn't solve my issue and I still have the exact same error.
How am I supposed to package the shared objects in a way that vosk will find them?
I could solve the issue with this config for electron, putting all the dependencies of vosk in the extraResources field:
"build": {
"extraResources": [
"node_modules/at-least-node/**/*",
"node_modules/builder-util-runtime/**/*",
"node_modules/debug/**/*",
"node_modules/ffi-napi/**/*",
"node_modules/fs-extra/**/*",
"node_modules/get-symbol-from-current-process-h/**/*",
"node_modules/get-uv-event-loop-napi-h/**/*",
"node_modules/graceful-fs/**/*",
"node_modules/jsonfile/**/*",
"node_modules/ms/**/*",
"node_modules/node-addon-api/**/*",
"node_modules/node-gyp-build/**/*",
"node_modules/ref-napi/**/*",
"node_modules/ref-struct-di/**/*",
"node_modules/sax/**/*",
"node_modules/universalify/**/*",
"assets/models/**/*"
],
"files": [
"dist/**/*",
"src/assets/icons/*",
"electron.js",
"package.json"
],
I also needed this lib.
It's now working as expected
I solved by updating my electron-builder configuration in package.json to be
{
"build": {
"asar": true,
"asarUnpack": [
"node_modules"
],
}
}
Then ensuring the unpacked path was used instead:
var dirPath = __dirname.includes('.asar') ? __dirname.replace('.asar', '.asar.unpacked') : __dirname;

Webpack bundle imports with an #

I am trying to bundle a Node Express server built with TypeScript using Webpack.
Compiling/Transpiling into one JavaScript file server.js works well, but the file does not seem to have all necessary imports included. If the file is in dist/server.js and there are still Node modules in node_modules/..., then starting the server using node dist/server.js works well. But if I copy the server.js to any other location without also copying the Node modules, and then start it, it does not find classes imported with an #.
Possible error:
mysystem:Desktop myuser$ node server.js
internal/modules/cjs/loader.js:582
throw err;
^
Error: Cannot find module '#overnightjs/core'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/Users/myuser/Desktop/server.js:1:1422)
at a (/Users/myuser/Desktop/server.js:1:172)
at Object.<anonymous> (/Users/myuser/Desktop/server.js:1:6473)
at a (/Users/myuser/Desktop/server.js:1:172)
at Object.<anonymous> (/Users/myuser/Desktop/server.js:1:6233)
at a (/Users/myuser/Desktop/server.js:1:172)
I think that I might have something missing in my Webpack configuration file, which is:
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: "./src/start.ts",
output: {
filename: "server.js",
path: path.resolve(__dirname, "dist")
},
node: {
// Need this when working with express, otherwise the build fails
__dirname: false, // if you don't put this is, __dirname
__filename: false, // and __filename return blank or /
fs: 'empty',
},
resolve: {
alias: {},
// Add '.ts', and '.tsx' as resolvable exteensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
externals: [nodeExternals()], // Need this to avoid error when working with Express
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
plugins: [
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['dist']
})
]
};
The versions I use:
Node (v10.13.0)
yarn (1.7.0)
Express (4.17.1)
TypeScript (3.7.4)
Webpack (4.41.4)
Webpack-CLI (3.3.10)
How can I also add imports starting with an # into the bundle in Webpack?
It is make sense, Your externals config tells webpack not to bundle node_modules into the bundle but require them at run time.
This means that if you are not copying node_modules to the new location, it will try to require it, and will fail.
Usually it is best practice not to bundle node_modules whenever you are creating a node bundle.
You have 2 choices:
Remove externals config - will increase bundle size cause it will contain all the node_modules that your app is using.
Installing a fresh node_modules on you new location, if this location is a production env, you can use npm install --production which will install only the dependencies without devDependencies.
Don't bundle modules when transpiling TypeScript. Standard practice is two download modules wherever you've deployed you server. Make sure to use the production flag if you're all done developing. npm i --production

unexpected token error with NPM? [duplicate]

I was experimenting on using Node version 6.2.1 with some of my code. Had plans to migrate most of the hyper-callback oriented codes to something that looks cleaner and maybe performs better.
I have no clue why, the terminal throws up an error when I try to execute the node code.
helloz.js
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ node helloz.js
/Users/bozzmob/Documents/work/nextgennms/rest/helloz.js:1
(function (exports, require, module, __filename, __dirname) { (async function testingAsyncAwait() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:456:3
BOZZMOB-M-T0HZ:rest bozzmob$ node -v
v6.2.1
What am I missing? Please throw me some light on the same.
Update 1:
I tried to use Babel as Quentin suggested, But, I am getting the following error still.
Updated Code-
require("babel-core/register");
require("babel-polyfill");
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ babel helloz.js > helloz.trans.js
SyntaxError: helloz.js: Unexpected token (3:7)
1 | require("babel-polyfill");
2 |
> 3 | (async function testingAsyncAwait() {
| ^
4 | await console.log("Print me!");
5 | })();
Async functions are not supported by Node versions older than version 7.6.
You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.
That said, versions of Node.js which don’t support async functions are now all past End Of Life and are unsupported, so if you are using an earlier version you should very strongly consider upgrading.
Nodejs supports async/await from version 7.6.
Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html
Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Babel.
install
npm install --save asyncawait
helloz.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
(async (function testingAsyncAwait() {
await (console.log("Print me!"));
}))();
If you are just experimenting you can use babel-node command line tool to try out the new JavaScript features
Install babel-cli into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
babel-node sample code : https://github.com/stujo/javascript-async-await/tree/15abac
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
Full webpack example : https://github.com/stujo/javascript-async-await
node v6.6.0
If you just use in development. You can do this:
npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev
the package.json would be like this:
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-plugin-transform-async-to-generator": "^6.16.0",
"babel-polyfill": "^6.20.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator"]
}
and then, run your async/await script like this:
./node_modules/.bin/babel-node script.js
Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:
npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev
the package.json would be like this:
"devDependencies": {
"babel-plugin-transform-async-to-generator": "6.24.1",
"babel-plugin-transform-runtime": "6.23.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
and then happy coding with async/await
include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json

How to get semantic/gulp/webpack to work in electron-react-boilerplate

I am trying to port a react app to electron using electron-react-boilerplate but I'm using semantic-ui which suggested being set up with gulp. electron-react-boilerplate uses webpack to handle all of its packaging and I can't get webpack +gulp to work so everything will package in the electron app.
I'm trying this link that explains how to pipe webpack configs through gulp tasks but I'm getting an "unexpected token import" error from the webpack config.
.babelrc
{
"presets": ["es2015", "stage-0", "react"],
"plugins": ["add-module-exports"],
"env": {
"production": {
"presets": ["react-optimize"],
"plugins": ["babel-plugin-dev-expression"]
},
"development": {
"plugins": ["tcomb"],
"presets": ["react-hmre"]
},
"test": {
"plugins": [
["webpack-loaders", { "config": "webpack.config.test.js", "verbose": false }]
]
}
}
}
simple gulpfile.js straight from the link above:
var gulp = require('gulp');
var webpack = require('webpack-stream');
gulp.task('default', function() {
return gulp.src('src/entry.js')
.pipe(webpack())
.pipe(gulp.dest('dist/'));
});
the webpack dev file is here,
note some of the names are changed between this boilerplate version and my project but otherwise it's the same.
the error:
Configurator>gulp
[09:52:40] Using gulpfile C:\git\Configurator\gulpfile.js
[09:52:40] Starting 'default'...
[09:52:40] 'default' errored after 8.28 ms
[09:52:40] C:\git\Configurator\webpack.config.development.js:7
import webpack from 'webpack';
^^^^^^
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Gulp.<anonymous> (C:\git\Configurator\gulpfile.js:7:18)
at module.exports (C:\git\Configurator\node_modules\orchestrator\lib\runTask.js:34:7)
the internet tells me that getting rid of the import errors should be as simple as using the 'es2015' preset in .babelrc but it's there and it's not helping.
I can get the dev server to work in the electron app with the semantic-ui stuff after the initial gulp build for semantic, but for some reason it doesn't build into the electron package when I try to package an installer to deploy this thing.
When I run the electron app dev server through webpack it works fine though, except I get two errors:
cannot set property exports of undefined
and
locals[0] does not appear to be a module object with hot module replacement API enabled
the latter stacktrace goes back to some semantic imports in one of my react files.
I'm totally at a loss as to how to make all this stuff work together.

Resources