My understanding is that we can use ES6 standard on the node js, if we install the node module - Babel. Below are my dependencies on package.json
"dependencies": {
"babel": "^6.23.0",
"express": "^4.16.4"
}
testFunction.js
export const fnc = () => {
return "test";
}
index.js
const test = require("./testFunction");
console.log(test);
Basically, I just want to import the user defined function on my index.js. But getting below error message:
(function (exports, require, module, __filename, __dirname) { export
const fnc = () => {
^^^^^^
SyntaxError: Unexpected token export
at new Script (vm.js:51:7)
at createScript (vm.js:138:10)
at Object.runInThisContext (vm.js:199:10)
at Module._compile (module.js:624:28)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
Any help would be appreciated!
Related
I'm trying to write a test case in a NextJS application using Jest. On running the test, below error occurs:
/Users/abhajan/Work/Tusk/tusk-app/node_modules/uuid/dist/esm-browser/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
10 | import { useAccount, useBalance, useNetwork, useProvider } from "wagmi";
11 | import Web3 from "web3";
> 12 |
| ^
13 | export default function BlockchainInfo() {
14 | // TODO: Check if user is authenticated first
15 | return (
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1422:14)
at Object.<anonymous> (node_modules/rpc-websockets/dist/lib/server.js:40:13)
at Object.<anonymous> (node_modules/rpc-websockets/dist/index.js:30:38)
at Object.<anonymous> (node_modules/#solana/web3.js/lib/index.cjs.js:15:21)
at Object.<anonymous> (node_modules/#moralisweb3/sol-utils/src/dataTypes/SolAddress/SolAddress.ts:2:1)
at Object.<anonymous> (node_modules/#moralisweb3/sol-utils/src/dataTypes/SolAddress/index.ts:1:1)
at Object.<anonymous> (node_modules/#moralisweb3/sol-utils/src/dataTypes/index.ts:1:1)
at Object.<anonymous> (node_modules/#moralisweb3/sol-utils/src/index.ts:1:1)
at Object.<anonymous> (node_modules/#moralisweb3/auth/src/methods/requestMessage.ts:1:1)
at Object.<anonymous> (node_modules/#moralisweb3/auth/src/MoralisAuth.ts:2:1)
at Object.<anonymous> (node_modules/#moralisweb3/auth/src/index.ts:1:1)
at Object.<anonymous> (node_modules/moralis/src/index.ts:3:1)
at Object.<anonymous> (components/blockchain-info/index.tsx:12:55)
at Object.<anonymous> (pages/index.tsx:10:62)
at Object.<anonymous> (__tests__/index.test.tsx:7:53)
Below is the setup for jest config in jest.config.js:
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
/** #type {import('jest').Config} */
const customJestConfig = {
// Add more setup options before each test is run
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
transformIgnorePatterns: ['node_modules/(?!uuid)/'],
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
Below is the test file index.test.tsx:
import { render } from '#testing-library/react';
import Home from 'pages/index';
import '#testing-library/jest-dom';
describe('Home', () => {
it('renders homepage unchanged', () => {
const { container } = render(<Home />);
expect(container).toMatchSnapshot();
});
});
On running the test file, the below error occurs:
Details:
/Users/abhajan/Work/Tusk/tusk-app/node_modules/uuid/dist/esm-browser/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
Not sure if the regex pattern in transformIgnorePatterns is correct or not. Any kind of help is appreciated :)
I can't access this module I'm exporting. I have no clue what's wrong.
I'm trying to export a database connection so it's available everywhere.
database.js
import { Sequelize } from 'sequelize';
var server = 'aggregatesqlserver.database.windows.net'
var database = 'AGGREGATEDEVDB'
var username = '****'
var password = '****'
var driver= '{ODBC Driver 17 for SQL Server}'
const sequelize = new Sequelize(database, username, password, {
host: server,
dialect: "mssql"
});
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
module.exports = sequelize;
When I try to access if from this script
main.ts
import { NestFactory } from '#nestjs/core';
import { NestExpressApplication } from '#nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './app.module';
import { createConnection, Connection} from "typeorm";
const db = require('./config/database');
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('hbs');
const [results, metadata] = await db.query("UPDATE [dbo].[storedProc] SET someData = RAND() WHERE columnID = 1");
await app.listen(3000);
}
bootstrap();
It gives me this error no matter what...
Error: Cannot find module './config/database'
Require stack:
- /Users/paytondugas/Desktop/RapidTek/nest/SQL/csp_copy/dist/main.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:885:15)
at Function.Module._load (internal/modules/cjs/loader.js:730:27)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/Users/paytondugas/Desktop/RapidTek/nest/SQL/csp_copy/src/main.ts:7:12)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Here's the file system
Any clue on the problem...?
This behavior happens because you try to import a Javascript file from Typescript file. You can try:
1.
import * as db from './config/database';
Add this characteristic to allow JS modules import in tsconfig.json or your tsconfig
{
"compilerOptions": {
"allowJs": true
}
}
Sometimes such conflicts happen due to using ES5 module syntax instead of ES6 module syntax.
To avoid such problem try using only one module syntax, either the es5 or the es6
Try using
import db from './config/database';
instead of
const db = require('./config/database');
I have below nodejs code to deploy smart contract from a file into local private ethereum network.
const fs = require('fs');
const Web3 = require('web3');
const solc = require('solc');
const web3 = new Web3();
web3.setProvider(web3.providers.HttpProvider('http://localhost:8545'));
const address = web3.eth.accounts[0];
const code = fs.readFileSync('../Calculator.sol').toString()
const compiledCode = solc.compile(code)
const abiDefinition = JSON.parse(compiledCode.contracts[':Calculator'].interface)
const byteCode = compiledCode.contracts[':Calculator'].bytecode
const CalcContract = web3.eth.contract(abiDefinition)
I've below dependencies in package.json
"dependencies": {
"ethereumjs-testrpc": "^6.0.3",
"fs": "0.0.1-security",
"solc": "^0.5.9",
"web3": "^1.0.0-beta.55"
}
When I run the program I get below error at line web3.setProvider(web3.providers.HttpProvider('http://localhost:8545'));
[raj#localhost first_truffle_project]$ sudo node js/example_deployer.js
/home/raj/Coding/Ethereum/first_truffle_project/js/example_deployer.js:6
web3.setProvider(web3.providers.HttpProvider('http://localhost:8545'));
^
TypeError: Cannot read property 'HttpProvider' of undefined
at Object.<anonymous> (/home/raj/Coding/Ethereum/first_truffle_project/js/example_deployer.js:6:33)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787: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:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
What is wrong with my program? How can I resolve this error?
Try like this :
web3 = new Web3(new Web3.providers.HttpProvider('node-url'))
Make sure your Web 3 version in package.json is
"web3": "^1.0.0-beta.37"
an I believe you want something like this. (Note the capitalization.)
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
I had a perfectly working relay modern app with 1.1.0 babel-plugin-relay + react-relay + react-compiler + graphql 0.10.x, react 15.5.x but since upgrading all of them to 1.4.1 and graphql to 0.11.7 and react to 16.0.0 I keep getting this error when running npm start:
ERROR in ./src/main.js
Module build failed: Error: BabelPluginRelay: Expected plugin context to include "types", but got:[object Object]
at BabelPluginRelay (/Users/johndoe/testing/atc/node_modules/babel-plugin-relay/lib/BabelPluginRelay.js:36:11)
at Object.<anonymous> (/Users/johndoe/testing/atc/src/babelRelayPlugin.js:28:18)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at /Users/johndoe/testing/atc/node_modules/babel-core/lib/transformation/file/options/option-manager.js:178:20
# multi (webpack)-dev-server/client?http://localhost:3333 ./src/main.js
webpack: Failed to compile.
with babel-plugin-relay like so:
babelRelayPlugin.js:
const babelRelayPlugin = require('babel-plugin-relay')
const { introspectionQuery, buildClientSchema, printSchema } = require('graphql/utilities')
const request = require('sync-request')
const fs = require('fs')
const path = require('path')
const schemaPath = path.join(__dirname, 'schema');
const graphqlHubUrl = 'https://myhub.com/dev/graphql'
const response = request('POST', graphqlHubUrl, {
qs: {
query: introspectionQuery
}
})
console.log('response ', response)
const schema = JSON.parse(response.body.toString('utf-8'))
console.log('schema ', schema)
const graphQLSchema = buildClientSchema(schema.data);
fs.writeFileSync(
`${schemaPath}.graphql`,
printSchema(graphQLSchema)
);
module.exports = babelRelayPlugin(schema.data, {
abortOnError: true
})
and webpack.config.js:
query: {
presets: ['env', 'react', 'stage-2'],
plugins: ['relay', 'transform-class-properties', __dirname + '/src/babelRelayPlugin']
}
the question is why ? and how I can fix it? because in the response I can clearly see types:
Solved it.
Had to change this:
module.exports = babelRelayPlugin(schema.data, {
abortOnError: true
})
to this:
module.exports = babelRelayPlugin(schema.data.__schema, {
abortOnError: true
})
I want to pass React Component from server-side, which is written in node.js.
Code(server.js):
var ReactDOMServer = require('react-dom/server');
var ReactApp = require('./console/ReactApp');
app.get('*', function(req, res, next){
var reactHtml = ReactDOMServer.renderToString(<ReactApp />);
res.render('index',
{reactOutput: reactHtml});
});
console/ReactApp.js:
var React = require('react');
var ReactApp = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
module.exports = ReactApp;
In both files, '<>' generated SyntaxError when running node server.js
var reactHtml = ReactDOMServer.renderToString(<ReactApp />);
^
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/.../www.js:7:11)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
that's is JSX. You need to transpile it before use or run it with babel-node (the latter is NOT a recommended method).
Or you can use transpiled code like this:
var reactHtml = ReactDOMServer.renderToString(React.createElement(ReactApp));
See full api of React.createElement here