I got a problem when I try to access the variable:process.env. It told me I got a syntax error and I'm 100% sure that my code is correct.
I want to know what problem with it
I tried check my codes over and over again. I can't find any syntax error.By the way, it's ok when I access the proceess varible. But when I try to access the process.env, it started to execute eval, which raised the error I mentioned before.
My code goes that :
src/global.vue
console.log(process.env);
The error I got:
Uncaught SyntaxError: Unexpected token :
at Object../node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue (app.js:1170)
at __webpack_require__ (app.js:679)
at fn (app.js:89)
at eval (App.vue?9e04:1)
at Object../src/App.vue (app.js:5245)
at __webpack_require__ (app.js:679)
at fn (app.js:89)
at eval (main.js:5)
at Object../src/main.js (app.js:5357)
at __webpack_require__ (app.js:679)
The app.js:1170 goes that:
eval("/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__components_headers__ = __webpack_require__(\"./src/components/headers.vue\");\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__components_blogfooter__ = __webpack_require__(\"./src/components/blogfooter.vue\");\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n\n// import axios from 'axios'\n\n\n/* harmony default export */ __webpack_exports__[\"a\"] = ({\n name: 'App',\n components: { 'headers': __WEBPACK_IMPORTED_MODULE_0__components_headers__[\"a\" /* default */],\n 'blog-footer': __WEBPACK_IMPORTED_MODULE_1__components_blogfooter__[\"a\" /* default */]\n },\n created: function created() {\n this.$store.dispatch('GET_BASIC');\n console.log(Object({\"NODE_ENV\":\"development\",\"SERVER\":http://localhost:8000}));\n }\n});//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcyEuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9zZWxlY3Rvci5qcz90eXBlPXNjcmlwdCZpbmRleD0wIS4vc3JjL0FwcC52dWUuanMiLCJzb3VyY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0E7QUFSQSIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue\n");
I solve it by adding double quotes on the value of the variable SERVER:
Old code
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
SERVER: 'http://localhost:8000'
})
New code
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
SERVER: '"http://localhost:8000"'
})
I don't know why it has no hint to tell me that thing. The grammar of config file is so weird that you need to put a quote outside an existed quote.
Can anyone tell me why?
After instpecting the error in app.js:1170 one can see that your process.env.serversomehow misses " - why that is no clue but i think this should be fixable now^^
currently:
{server: http://localhost:8000}
but should be
{server:"http://localhost:8000"}
I had a similar problem when working in a project with webpack, I made a configuration of the .env to node and to the test environment, but when running in the web environment, this same error message, as if the process. envdid not exist. In my case I was using the dotenv lib, so it was pretty simple to solve, I just saw that theJSON.stringifysetting inDefinePlugin` was missing.
Resolved configuring it this way:
new webpack.DefinePlugin({
"process.env": JSON.stringify(dotenv.parsed),
})
Related
I am just practicing creating a GitHub app. Part of the Octokit it says that I can use the createNodeMiddleware. Now that might not necessarily be as simple with next.js; however, the problem that I am having is actually a compiler error (it seems) where it says that it cannot read properties of undefined (reading 'substr') when I am trying to just create a new instance of the App object.
Here is my code
import { Octokit, App } from "octokit";
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
const myApp = new App({
appId: 123,
privateKey: "",
});
return NextResponse.redirect(new URL('/about-2', request.url))
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/about/:path*',
}
When it executes the line for const myApp = new App({... it throws this error. Any ideas on where to start with this? I realize that I may need to manually make the routes that it creates with the middleware in the end. But I was hoping to at least be able to create an instance of the App with Octokit as it seems like that will be necessary no matter what functionality that I want from octokit. This is a nextjs app bootstraped with create-next-app and the typescript template.
Server Error
TypeError: Cannot read properties of undefined (reading 'substr')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
<unknown>
node_modules\universal-user-agent\dist-web\index.js (6:0)
getUserAgent
node_modules\universal-user-agent\dist-web\index.js (6:26)
eval
node_modules\#octokit\endpoint\dist-web\index.js (359:64)
(middleware)/./node_modules/#octokit/endpoint/dist-web/index.js
evalmachine.<anonymous> (138:1)
__webpack_require__
evalmachine.<anonymous> (37:33)
fn
evalmachine.<anonymous> (269:21)
eval
webpack-internal:///(middleware)/./node_modules/#octokit/request/dist-web/index.js (5:75)
(middleware)/./node_modules/#octokit/request/dist-web/index.js
evalmachine.<anonymous> (248:1)
__webpack_require__
evalmachine.<anonymous> (37:33)
fn
evalmachine.<anonymous> (269:21)
eval
webpack-internal:///(middleware)/./node_modules/#octokit/core/dist-web/index.js (8:74)
I have the following setup:
// uuid-wrapper.ts
import { v4 as uuidV4 } from 'uuid';
const uuid: () => string = uuidV4;
export { uuid };
// uuid-wrapper.spec.ts
import { uuid } from './uuid-wrapper';
describe('uuid-wrapper', () => {
console.log(uuid());
});
This works fine runtime, but it breaks in test. I'm trying to migrate to Jest 29 and I'm getting the following error:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
From uuid's repo I found a workaround which, after applied and my jest.config.js looks like this:
module.exports = {
moduleNameMapper: {
uuid: require.resolve("uuid"),
},
};
This gives me a different error but I still have no idea what it means:
> jest uuid-wrapper --no-coverage
FAIL src/uuid-wrapper/uuid-wrapper.spec.ts
● Test suite failed to run
TypeError: (0 , uuid_wrapper_1.uuid) is not a function
In fact, any function I export from this file (uuid-wrapper.ts) is not resolved. I have other tests that follow a similar pattern of reexporting packages but only this one breaks. I'm using uuid 9.0.0 and jest 29.1.2.
Edit: After a bit more testing, it turns out that anything I import into the test is "not a function".
uuid ships as an ESModule and Jest should not need to transform it. Add it to your transformIgnorePatterns in your Jest config:
module.exports = {
transformIgnorePatterns: ['node_modules/(?!(uuid))'],
}
Edit: After a bit more testing, it turns out that anything I import into the test is "not a function".
I had very similar symptoms once: builds and works as excepted, yet ...is not function in jest. The culprit was a circular dependency I accidentally introduced with my story. Maybe check for that.
As I suspected, the issue was in the naming. Renaming the files and directory to just wrapper solved the issue.
I need to import a file into my project when an environment variable is set, say dist/built.esm.js. It's implied that when the environment variable is set, the file will exist, otherwise it may or may not exist. It seems straightforward to just wrap a call to import in an if statement that checks for the environment variable, but Vue throws the below warning even if the if statement never passes:
And the code:
if (process.env.VUE_APP_USE_COMPILED == 'true') {
const compiledPackage = require('./dist/built.esm.js')
Vue.use(compiledPackage)
}
Setting the if statement to always be false in a nondeterminate way (setting a string var and then comparing it to a different value, instead of just if (false)) results in the same problem, which rules out any possibility of the environment variable being 'true' when it isn't supposed to be.
A temporary workaround I found is to wrap the import in a try/catch, which instead displays a warning instead of an error:
How can I get rid of the errors and warnings completely? I do want it to still error if the file doesn't exist but the environment variable has been set to true, but it shouldn't fail or warn on compilation if the statement hasn't even executed yet.
Does this work?
if (process.env.VUE_APP_USE_COMPILED == 'true') {
import('dist/built.esm.js')
.then(obj => Vue.use(obj))
.catch(err => console.log(err));
}
I managed to figure this out on my own. I used the resolve.alias property in the Webpack configuration to allow a 'soft fail' when the file doesn't exist. I changed my import to use an alias (my-compiled-package-alias), which would conditionally resolve to either the built file or an empty dummy file (dev/import-dummy.js). I had to use resolve.alias rather than resolve.fallback, since Vue2 uses Webpack v4 which doesn't include the latter property.
My updated code:
if (process.env.VUE_APP_USE_COMPILED == 'true') {
const compiledPackage = require('my-compiled-package-alias')
Vue.use(compiledPackage)
}
In my vue.config.js:
module.exports = {
...
configureWebpack: {
resolve: {
alias: {
"my-compiled-package-alias":
process.env.VUE_APP_USE_COMPILED ? "./dist/built.esm.js": "./import-dummy.js"
}
}
},
...
}
but it shouldn't fail or warn on compilation if the statement hasn't even executed yet
Compilation happens before execution. If you get a compile error, that means something went wrong before your code was executed, including any conditionals.
What I believe happens here is that you're using webpack, and it's trying to include dist/built.esm.js in your bundle. Behind the scenes, webpack actually replaces require with some magic. To get around this, use __non_webpack_require__ instead
You could try setting up a compile-time constant using DefinePlugin in your webpack config, maybe something like
plugins: [
new webpack.DefinePlugin({
// this is resolved compile-time
USE_COMPILED: process.env.VUE_APP_USE_COMPILED == 'true'
})
]
Then, in your code
if (USE_COMPILED) require('./dist/built.esm.js')
Here the value of USE_COMPILED should be replaced by webpack compile-time with true if your environment var is set to 'true', and false otherwise.
I have created a lambda function to get the list of items stored in dynamodb. Then i executed npm run build command after which i got .js files. I zipped the dist contents along with node modules, webpack.config.js and package.json and uploaded it. When i try to test it, am getting the following error. But there is no error in the code as far as i checked.
{
"errorType": "Runtime.UserCodeSyntaxError",
"errorMessage": "SyntaxError: Cannot use import statement outside a module",
"trace": [
"Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module",
" at _loadUserApp (/var/runtime/UserFunction.js:98:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:43:30)",
" at Module._compile (internal/modules/cjs/loader.js:956:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)",
" at Module.load (internal/modules/cjs/loader.js:812:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:724:14)",
" at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)",
" at internal/main/run_main_module.js:17:11"
]
}
I had the same error with node uuid module. Importing and using it as below fixed my issue:
'use strict';
const uuid = require('uuid'); // <-- how to import
exports.hello = async (event) => {
// ...
uniqueId = uuid.v4(); // <-- how to use it
// ...
};
I was ok with using require() for the longest time BUT certain packages like netlify cannot be loaded in lambda via require().
But AWS improved this ES vs commonJS import statement support early 2022... See here. Sadly not well described.
The following steps are maybe not perfect but worked for me:
Switch to NodeJs v14 on your AWS function if you didn't already
Pack the packages that you want to use once more and don't just have a nodejs folder but also a node14 folder. The node14 folder is mentioned here and I think essential. In case you forgot how to create lambda packages follow the docs here.
Create a lib.mjs file and load the package via import from /opt/nodejs/node14/node_modules/[my-package]/[maybe-some-subfolder]/index.js.
You can export what you need as object from lib.mjs and load it from index.js
lib.mjs:
// lib.mjs
import { NetlifyAPI } from "/opt/nodejs/node14/node_modules/netlify/src/index.js";
import { Route53Client } from "/opt/nodejs/node14/node_modules/#aws-sdk/client-route-53/dist-cjs/index.js";
export function loadPackages() {
return { NetlifyAPI, Route53Client };
}
Index.js:
//index.js:
import { loadPackages } from './lib.mjs';
export async function handler(event) {
const { NetlifyAPI, Route53Client } = loadPackages();
//TODO: business logic
}
This took me a long time to research and my approach is likely not perfect. I was forced to find a solution to load netflify and it only worked via import statement. I'm happy to get feedback in the comments and I am willing to adjust my tutorial accordingly.
Currently I'd generally still recommend to stick with require() if you can. If not I hope I could help.
PS: webpack is not needed in this approach.
This might be pretty late but i fixed mine by using require instead of import when importing modules
You have a problem with your import. Review your code (imports parts) and see if your IDE detects any errors. For my case, it was :
import Jimp from 'jimp/es'
I changed it to
import Jimp from 'jimp'
And now everything works.
I'm currently creating a Dialogflow chatbot in nodejs and upon deploying my code I get an error message. I've attempted to uncomment most things out to just be left with the base functioning code and I am still unable to get it working. I'm not exactly sure what the issue is here
'use strict';
import {getAPIresponse} from "./api/index.js";
// const http = require('https');
// const respond = fulfillmentText => {
// return {
// statusCode: 200,
// body: JSON.stringify({
// fulfillmentText
// }),
// headers: {
// "Content-Type": "application/json"
// }
// }
//
// };
module.exports.dining = async (event,context) => {
const incoming= JSON.parse(event.body).queryResult;
console.log(`INCOMING: ${incoming.parameters.hall}`);
const {
displayName
} = incoming.intent;
console.log(displayName);
//const menu = getAPIresponse('https://esb.prod.uds.harvard.edu/api/dining/2.0/','events?locationId=36');
//console.log(menu);
// if(displayName === 'dining'){
// if(incoming.parameters.meal === 'breakfast'){
// //get's dining hall code to include in API request
// const hall = getCode(incoming.parameters.hall);
// //generate response from API based off of parameters passed by user
// const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0/","events?locationId=${hall}", hall);
// console.log(menu);
// }
// if(incoming.parameters.meal === 'lunch'){
// //get's dining hall code to include in API request
// const hall = getCode(incoming.parameters.hall);
// //generate response from API based off of parameters passed by user
// const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0","/events", hall);
// }
// if(incoming.parameters.meal === 'dinner'){
// //get's dining hall code to include in API request
// const hall = getCode(incoming.parameters.hall);
// //generate response from API based off of parameters passed by user
// const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0","/events", hall);
// }
// }
};
Almost everything is commented out and I still get the error message that reads
2019-07-02 16:31:33.351 (-04:00) undefined ERROR Uncaught Exception {
"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected tok
en {","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected token {"," at
_loadUserApp (/var/runtime/UserFunction.js:98:13)"," at Object.module.exports.loa
d (/var/runtime/UserFunction.js:140:17)"," at Object.<anonymous> (/var/runtime/ind
ex.js:36:30)"," at Module._compile (internal/modules/cjs/loader.js:701:30)"," a
t Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)"," at Modu
le.load (internal/modules/cjs/loader.js:600:32)"," at tryModuleLoad (internal/modu
les/cjs/loader.js:539:12)"," at Function.Module._load (internal/modules/cjs/loader
.js:531:3)"," at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)",
" at startup (internal/bootstrap/node.js:283:19)"]}
Worked for me: Updating Node.js version of lambda
I got this error because lambda was defined to execute with Node.js 12.x, when I changed it to Node.js 14.x (as on my local machine) it worked
If it works - and you're generally using the serverless package to automate the deployment of your lambda - don't forget to update your serverless.yml file accordingly
AWS Lambda does not support the ES6 import specifier as you've written here
import {getAPIresponse} from "./api/index.js";
because the ES6 import syntax isn't yet supported by default in Node.js (note: my lambda runtime was set to Node.js 10.x).
Illustration:
I was having this issue as well when importing a library at the top of my lambda distribution's index.js file.
The stacktrace Uncaught Exception { "errorType":"Runtime.UserCodeSyntaxError", ... unexpected token import found ... blabla... } ... was thrown in my lambda function when I used the import syntax:
import awsServerlessExpress from 'aws-serverless-express';
exports.handler = (event, context) => {
console.log('hello world!')
};
But not in this version below when I just used the standard module require syntax.
const awsServerlessExpress = require('aws-serverless-express');
exports.handler = (event, context) => {
console.log('hello world!')
};
For me, it was the import syntax that was causing the SyntaxError exceptions, but do take note that, for you, any JavaScript syntax not supported by your current Node.js runtime will throw this exception.
A couple of solutions:
Change all import statements to standard module require statements and keep using whatever default JavaScript flavour is supported by your configured Node.js runtime.
Use a transpiler like Babel w/ Webpack to transpile your ES6 JavaScript before deploying to the cloud.
Use the quick solution nicely described by Yitzchak below :) Just bump the NodeJS version on your Lambda Dashboard.
In my case, I pasted code from another lambda which had node version 14.
But my current lambda node version was 12.
The code I pasted was using optional chaining(?.) in one line. Removed it, deployed code and it worked fine.
If you are using TypeScript and encounter this error make sure the target you set in tsconfig.json matches your targeted nodejs version. For a list of recommended settings visit Node Target Mapping
For example I was targeting node.js 12 and using ES2020. Changing this to ES2019 fixed my issue.
Sometimes in lambda, when we click on Deploy all the changes are not deployed. Refresh the page and check for syntax errors.
or at least that's what was the problem in my case.
In my case I changed the tsconfig.json module setting:
"module": "es2015"
to
"module": "CommonJS",
ref: https://www.typescriptlang.org/tsconfig#module