ES6/ES7 support with serverless - serverless-framework

I have few serverless project created without using ES6/ES7 support. In our new project, i wanted to integrate this with serverless but not able to get it going.
Here is my serverless.yml file
#sls offline start --skipCacheInvalidation
service: test
provider:
name: aws
runtime: nodejs8.10 # set node.js runtime
memorySize: 1024 # set the maximum memory of the Lambdas in Megabytes
timeout: 300 # the timeout is 10 seconds (default is 6 seconds)
stage: ${opt:stage, 'dev'} #${self:provider.stage} # setting the env stage to dev, this will be visible in the routes
region: us-east-1
logRetentionInDays: 14 # Set the default RetentionInDays for a CloudWatch LogGroup
deploymentBucket:
name: api-test
# custom:
# stage: ${opt:stage, self:provider.stage}
environment: ${file(env.yml):${self:provider.stage}}
plugins:
- serverless-webpack
- serverless-offline
# serverless optimization
package:
individually: true
# serverless-webpack configuration
# Enable auto-packing of external modules
custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules: true
functions:
createCampaign:
handler: src/Campaign.CreateCampaign
name : campaign-createcampaign-${self:provider.stage} #custom lambda name instead of auto generated
description: To create campaign
events:
- http:
path: campaign
method: post
cors: true
getAllCampaign:
handler: src/Campaign.GetCampaign
name : campaign-getall-${self:provider.stage} #custom lambda name instead of auto generated
description: To retrieve all campaign
events:
- http:
path: campaign
method: get
cors: true
My campaign.js is under /src folder in my code. I tried this using https://medium.com/#kilgarenone/write-es6-es7-in-serverless-framework-using-babel-7-and-webpack-4-5bd742168e1a
My webpack config is following.
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
//entry: slsw.lib.entries,
entry: {handler : './src/Campaign.js'},
target: 'node',
// Generate sourcemaps for proper error messages
devtool: 'source-map',
// Since 'aws-sdk' is not compatible with webpack,
// we exclude all node dependencies
externals: [nodeExternals()],
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
optimization: {
// We no not want to minimize our code.
minimize: false,
},
performance: {
// Turn off size warnings for entry points
hints: false,
},
// Run babel on all .js files and skip those in node_modules
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: __dirname,
exclude: /node_modules/,
},
],
},
};
My package.json is
{
"name": "orim-api",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.4",
"#babel/preset-env": "^7.4.4",
"babel-loader": "^8.0.5",
"babel-plugin-source-map-support": "^2.0.1",
"serverless-offline": "^4.9.4",
"serverless-webpack": "^5.3.0",
"webpack": "^4.30.0",
"webpack-node-externals": "^1.7.2"
},
"dependencies": {
"dotenv": "^7.0.0",
"mongoose": "^5.5.5",
"source-map-support": "^0.5.12"
}
}
My .babelrc file is
{
"plugins": ["source-map-support", "transform-runtime"],
"presets": [
["env", { "node": "8.10" }],
"stage-3"
]
}
When i execute sls offline start --SkipCacheInvalidateion, i get following warning
WARNING in ./src/Campaign.js 5:12-29
"export 'connectToDatabase' was not found in '../db'
And it seems like webpack and babel-loader isn't transpile my entire code

From the doc, this is something you can try:
// webpack.config.js
const _ = require('lodash');
const slsw = require('serverless-webpack');
module.exports = {
...
entry: _.assign({
handler : './src/Campaign.js'
}, slsw.lib.entries),
...
};

Related

inject is not defined - CodeceptJs and CucumberJs

It's my first time using CodeceptJs and I'm struggling to run my feature file as the IDE asks me to implement steps for my scenario but this is already done, so I feel it may be searching for them somewhere other than the specified under the codecept.conf.js file?
When I run npx codeceptjs gherkin:steps or snippets on the terminal I get this message saying Could not include object Step Definition from ./step_definitions/steps.js from module '/Users/myUser/IdeaProjects/codeceptjs_webdriver/step_definitions/steps.js' The "from" argument must be of type string. Received undefined .
I then move the step_definitions folder to inside features as read that this would be the default location for these and now get an inject is not defined error, which may be the actual cause for the issue I'm getting, but not sure what to do to fix it.
I've tried on IntelliJ Ultimate, Webstorm and VSCode but get the same on all of them.
basic.feature
Feature: Business rules
In order to achieve my goals
As a persona
I want to be able to interact with a system
Scenario: do something
Given I have a defined step
steps.js
const {Given} = require('cucumber');
const {I} = inject();
Given(/^I have a defined step$/, function () {
I.amOnPage('/');
});
codecept.conf.js
exports.config = {
output: './output',
helpers: {
WebDriver: {
url: 'https:www.google.com',
browser: 'chrome'
}
},
include: {
I: './steps_file.js'
},
mocha: {},
bootstrap: null,
teardown: null,
hooks: [],
gherkin: {
features: './features/*.feature',
steps: ['./step_definitions/steps.js']
},
plugins: {
screenshotOnFail: {
enabled: true
},
pauseOnFail: {},
retryFailedStep: {
enabled: true
},
tryTo: {
enabled: true
}
},
tests: './*_test.js',
name: 'codeceptjs_webdriver'
}
package.json
{
"name": "codeceptjs_webdriver",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"codeceptjs": "^3.0.0",
"cucumber": "^5.0.1"
},
"dependencies": {
"#codeceptjs/configure": "^0.6.0"
},
"description": ""
}
IntelliJ Ultimate 2020.2
And here my Github repo
Thank you very much.
It's working now and I've come back to update it here if useful to someone else.
Was able to keep the steps under step_definitions/steps folder (not the one inside the features folder). To fix the non implemented issue had to install the wdio dependency. In order for this to take effect properly through running npm install both node_modules and package-lock.json had to be deleted to be freshly regenerated.
updated package.json
{
"name": "codeceptjs_webdriver",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "npx codeceptjs run"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {},
"dependencies": {
"#wdio/selenium-standalone-service": "^6.6.2",
"codeceptjs": "^2.6.8",
"codeceptjs-assert": "0.0.4",
"webdriverio": "6.3.6"
},
"description": ""
}
updated codecept.conf.js
exports.config = {
output: './output',
helpers: {
WebDriver: {
url: 'https://www.google.com',
browser: 'chrome'
}
},
include: {
I: './steps_file.js'
},
mocha: {},
bootstrap: null,
teardown: null,
hooks: [],
gherkin: {
features: './features/*.feature',
steps: ['./step_definitions/steps.js']
},
plugins: {
wdio: {
enabled: true,
services: ['selenium-standalone']
// additional config for service can be passed here
},
screenshotOnFail: {
enabled: true
},
pauseOnFail: {},
retryFailedStep: {
enabled: true
},
},
tests: './*_test.js',
name: 'codeceptjs_webdriver'
}

Critical dependency: the request of a dependency is an expression, vue.js

My testing-app is compiling fine, except that I get this warning:
" Critical dependency: the request of a dependency is an expression"
(base) marco#pc01:~/webMatters/vueMatters/PeerJS-VueJS-Test$ npm run serve
> testproject#0.1.0 serve /home/marco/webMatters/vueMatters/PeerJS-VueJS-Test
> vue-cli-service serve
INFO Starting development server...
98% after emitting CopyPlugin
WARNING Compiled with 1 warnings
7:22:25 PM
warning in ./node_modules/peerjs/dist/peerjs.min.js
Critical dependency: the request of a dependency is an expression
App running at:
- Local: http://localhost:8080
- Network: http://ggc.world/
Note that the development build is not optimized.
To create a production build, run npm run build.
I read around that it might depend of webpack, but didn't find how to put it right.
This is webpack.config.js :
{
"mode": "development",
"output": {
"path": __dirname+'/static',
"filename": "[name].[chunkhash:8].js"
},
"module": {
"rules": [
{
"test": /\.vue$/,
"exclude": /node_modules/,
"use": "vue-loader"
},
{
"test": /\.pem$/,
"use": "file-loader"
}
]
},
node: {
__dirname: false,
__filename: false
},
resolve: {
extension: ['*', '.pem'],
},
devServer: {
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
https: true,
compress: true,
public: 'ggc.world:8080'
}
}
Any ideas about how to solve it?
The following code works for me. Edit vue.config.js and add webpack config:
configureWebpack: {
module: {
exprContextCritical: false
}
}
const webpack = require('webpack');
module.exports = {
// ... your webpack configuration ...
plugins: [
new webpack.ContextReplacementPlugin(
/\/package-name\//,
(data) => {
delete data.dependencies[0].critical;
return data;
},
),
]
}
try this one
For people coming here using CRA and having trouble with PeerJS, install react-app-rewired and use the following override config and it should work.
/* config-overrides.js */
const webpack = require('./node_modules/webpack')
module.exports = function override (config, env) {
if (!config.plugins) {
config.plugins = []
}
config.plugins.push(
new webpack.ContextReplacementPlugin(
/\/peerjs\//,
(data) => {
delete data.dependencies[0].critical
return data
}
)
)
return config
}
It seems it is an error between the library bundler (parcel) and CRA bundler (webpack), and I couldn't find any official fix on the way.

Why babelConfig not working in webpack encore?

I want to add support for async / await functions for my project.
I install
"#babel/core": "^7.2.0",
"#babel/plugin-transform-runtime": "^7.2.0",
"#babel/preset-env": "^7.2.0",
"#babel/preset-es2015": "^7.0.0-beta.53",
"#babel/preset-stage-2": "^7.0.0",
"#babel/runtime": "^7.2.0",
It's my webpack.config.js
const Encore = require('#symfony/webpack-encore');
Encore
.setOutputPath('public/build')
.setPublicPath('/build')
.addEntry('app', './assets/app.js')
.enableSourceMaps(!Encore.isProduction())
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableVueLoader()
.configureBabel(function(babelConfig) {
babelConfig.presets.push('#babel/preset-env');
babelConfig.presets.push('#babel/preset-stage-2');
babelConfig.plugins.push('#babel/plugin-transform-runtime');
})
;
const config = Encore.getWebpackConfig();
config.externals = {
mode: 'development',
// global app config object
config: JSON.stringify({
apiUrl: 'http://localhost:80',
devServer: {
public: 'http://localhost:3000',
disableHostCheck: true,
},
})
};
config.node = {
fs: "empty"
};
module.exports = config;
When I run a server dev, I get an error.
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Duplicate plugin/preset detected.
If you'd like to use two separate instances of a plugin,
they need separate names, e.g.
plugins: [
['some-plugin', {}],
['some-plugin', {}, 'some unique name'],
]
I can not understand what the problem is.
I also created a .babelrc file and wrote the same configuration in it. But unfortunately, this did not help (
Use .babelrc for change babel config like this. This file should be in your project root
{
"plugins": ["#babel/plugin-transform-runtime"],
"presets": [
[
"#babel/preset-env",
...
],
...
]
}
Then remove this from your webpack.config.js
.configureBabel(function(babelConfig) {
babelConfig.presets.push('#babel/preset-env');
babelConfig.presets.push('#babel/preset-stage-2');
babelConfig.plugins.push('#babel/plugin-transform-runtime');
})

Proper Jest configuration with React-native 0.56

After upgrading to react-native 0.56 I'm experiencing tons of babel reated errors on jest specs that used to run just fine.
I realize that react-native 0.56 requires babel7 and that's probably related but I don't have enough experience/understaanding in babel to figure out what I'm missing.
Some error examples:
/xxx/spec/Bootstrap.test.js:6
import thunk from 'redux-thunk';
^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
another:
import { rootReducer } from '../store';
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
My package.json jest config is as follows:
"jest": {
"preset": "react-native",
"collectCoverage": true,
"coverageReporters": [
"cobertura",
"lcov"
],
"coverageDirectory": "coverage",
"globals": {
"__TEST__": true
},
"moduleNameMapper": {
"styled-components": "<rootDir>/node_modules/styled-components/dist/styled-components.native.cjs.js"
},
"moduleDirectories": [
"node_modules",
"/"
],
"transformIgnorePatterns": [
"node_modules/(?!react-native|react-navigation)/"
],
"setupFiles": [
"jest-localstorage-mock",
"./node_modules/appcenter/test/AppCenterMock.js",
"./node_modules/appcenter-analytics/test/AppCenterAnalyticsMock.js",
"./node_modules/appcenter-crashes/test/AppCenterCrashesMock.js"
]
},
.babelrc is defined as follows:
{
"presets": ["react-native"],
"env": {
"development": {
"plugins": ["transform-class-properties"]
},
"test": {
"plugins": ["transform-class-properties"]
}
}
}
I also have the following devdependencies:
"#babel/core": "^7.0.0-beta.52",
"babel-core": "^7.0.0-beta.52",
"babel-eslint": "~8.2.5",
"babel-plugin-module-resolver": "^3.1.1",
"babel-plugin-transform-class-properties": "~6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-preset-expo": "~4.0.0",
"babel-preset-react-native": "^5.0.1",
"babel-preset-react-native-stage-0": "^1.0.1",
"babel-preset-stage-0": "^6.24.1",
I've tried several approaches but couldn't progress much.
Besides the jest environment, the application runs fine.
Details of the workaround I did to move on, while 0.57 wasn't ready:
Basically I had to create 2 config files:
jest-acceptance.config (with the following relevant snippets)
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/custom_b7_processor.js"
},
"testRegex": "(/test/.*|(\\.|/)spec)\\.js$",
jest-unit.config (with the following relevant snippets)
"preset": "react-native",
"testRegex": "(/test/.*|(\\.|/)test)\\.js$",
That custom_b7_processor, is some sort of internal code from react-native:
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* #format
* #flow
*/
/* eslint-disable */
'use strict';
const {transformSync: babelTransformSync} = require('#babel/core');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const babelRegisterOnly = require('metro-babel-register');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
const generate = require('#babel/generator').default;
const nodeFiles = RegExp(
[
'/local-cli/',
'/metro(?:-[^/]*)?/', // metro, metro-core, metro-source-map, metro-etc
].join('|'),
);
const nodeOptions = babelRegisterOnly.config([nodeFiles]);
babelRegisterOnly([]);
/* $FlowFixMe(site=react_native_oss) */
const transformer = require('metro/src/reactNativeTransformer');
module.exports = {
process(src /*: string */, file /*: string */) {
if (nodeFiles.test(file)) {
// node specific transforms only
return babelTransformSync(
src,
Object.assign(
{filename: file},
{sourceType: 'script', ...nodeOptions, ast: false},
),
).code;
}
const {ast} = transformer.transform({
filename: file,
localPath: file,
options: {
ast: true, // needed for open source (?) https://github.com/facebook/react-native/commit/f8d6b97140cffe8d18b2558f94570c8d1b410d5c#r28647044
dev: true,
inlineRequires: true,
platform: '',
projectRoot: '',
retainLines: true,
sourceType: 'unambiguous', // b7 required. detects module vs script mode
},
src,
plugins: [
[require('#babel/plugin-transform-block-scoping')],
// the flow strip types plugin must go BEFORE class properties!
// there'll be a test case that fails if you don't.
[require('#babel/plugin-transform-flow-strip-types')],
[
require('#babel/plugin-proposal-class-properties'),
// use `this.foo = bar` instead of `this.defineProperty('foo', ...)`
{loose: true},
],
[require('#babel/plugin-transform-computed-properties')],
[require('#babel/plugin-transform-destructuring')],
[require('#babel/plugin-transform-function-name')],
[require('#babel/plugin-transform-literals')],
[require('#babel/plugin-transform-parameters')],
[require('#babel/plugin-transform-shorthand-properties')],
[require('#babel/plugin-transform-react-jsx')],
[require('#babel/plugin-transform-regenerator')],
[require('#babel/plugin-transform-sticky-regex')],
[require('#babel/plugin-transform-unicode-regex')],
[
require('#babel/plugin-transform-modules-commonjs'),
{strict: false, allowTopLevelThis: true},
],
[require('#babel/plugin-transform-classes')],
[require('#babel/plugin-transform-arrow-functions')],
[require('#babel/plugin-transform-spread')],
[require('#babel/plugin-proposal-object-rest-spread')],
[
require('#babel/plugin-transform-template-literals'),
{loose: true}, // dont 'a'.concat('b'), just use 'a'+'b'
],
[require('#babel/plugin-transform-exponentiation-operator')],
[require('#babel/plugin-transform-object-assign')],
[require('#babel/plugin-transform-for-of'), {loose: true}],
[require('#babel/plugin-transform-react-display-name')],
[require('#babel/plugin-transform-react-jsx-source')],
],
});
return generate(
ast,
{
code: true,
comments: false,
compact: false,
filename: file,
retainLines: true,
sourceFileName: file,
sourceMaps: true,
},
src,
).code;
},
getCacheKey: createCacheKeyFunction([
__filename,
require.resolve('metro/src/reactNativeTransformer'),
require.resolve('#babel/core/package.json'),
]),
};
At my .babelrc I had to include the following:
"presets": ["./node_modules/babel-preset-react-native-b6"],
That is pointing to a fork I made of the babel preset that React-native was using at 0.56-
https://github.com/lhrolim/babel-preset-react-native.
At my package.json I had te following babel dependencies
"babel-preset-react-native": "~5.0.2",
"babel-preset-react-native-b6": "github:lhrolim/babel-preset-react-native",
The test scripts I used then:
"test": "npm run test-acc && npm run test-unit",
"test-acc": "jest --config=jest_acceptance-config.json",
"test-unit": "jest --config=jest_unit-config.json",
I believe there might be some redundancies here and there, but that's what worked for me.

webpack fail to bundle sequelize

I just currently working on Express js+typescript with Sequelize ORM and want to bundle using Webpack. The problem is I got warning and fail each time trying to bundle.
Here is my warning/error message:
WARNING in ./~/sequelize/lib/dialects/mysql/connection-manager.js
Module not found: Error: Can't resolve 'mysql' in 'D:\Project\MyMe\node_modules\sequelize\lib\dialects\mysql'
# ./~/sequelize/lib/dialects/mysql/connection-manager.js 20:17-33
# ./~/sequelize/lib/dialects/mysql/index.js
# ./~/sequelize/lib/sequelize.js
# ./~/sequelize/index.js
# ./src/server/models/index.js
# ./src/server/controllers/TopUp.ts
# ./src/server/controllers/index.ts
# ./src/router/router.ts
# ./src/App.ts
# ./src/index.ts
WARNING in ./~/express/lib/view.js
80:29-41 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/sequelize.js
686:60-73 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/dialects/mysql/connection-manager.js
18:17-60 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/dialects/mssql/connection-manager.js
18:15-71 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/dialects/postgres/connection-manager.js
20:14-57 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/dialects/sqlite/connection-manager.js
22:15-71 Critical dependency: the request of a dependency is an expression
ERROR in ./~/pg/lib/native/index.js
Module not found: Error: Can't resolve 'pg-native' in 'D:\Project\MyMe\node_modules\pg\lib\native'
# ./~/pg/lib/native/index.js 9:13-33
# ./~/pg/lib/index.js
# ./~/sequelize/lib/dialects/postgres/connection-manager.js
# ./~/sequelize/lib/dialects/postgres/index.js
# ./~/sequelize/lib/sequelize.js
# ./~/sequelize/index.js
# ./src/server/models/index.js
# ./src/server/controllers/TopUp.ts
# ./src/server/controllers/index.ts
# ./src/router/router.ts
# ./src/App.ts
# ./src/index.ts
Here is my package.json:
"devDependencies": {
"#types/body-parser": "^1.16.3",
"#types/chai": "^3.5.2",
"#types/chai-http": "0.0.30",
"#types/debug": "0.0.29",
"#types/express": "^4.0.35",
"#types/mocha": "^2.2.41",
"#types/morgan": "^1.7.32",
"#types/node": "^7.0.18",
"chai": "^3.5.0",
"chai-http": "^3.0.0",
"mocha": "^3.3.0",
"ts-loader": "^2.0.3",
"ts-node": "^3.0.4",
"typescript": "^2.3.2",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"
},
"dependencies": {
"body-parser": "^1.17.1",
"debug": "^2.6.6",
"express": "^4.15.2",
"morgan": "^1.8.1",
"pg": "^6.1.5",
"pg-hstore": "^2.3.2",
"sequelize": "^3.30.4"
}
Below is my webpack.config.js
var path = require('path');
var webpack = require('webpack')
var fs = require('fs')
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
loaders: [
{
test: /\.ts?$/,
loader: 'ts-loader',
exclude: /node_modules/,
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
devServer: {
port: 3000
},
target: 'node'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Fyi, before I'm adding Sequelize to my project its bundle fine with Express+typescript only. I know there is something I'm missing because I'm still new to webpack env. Thanks.
I think that's because sequalize is made for nodejs. Not every module is "compatible". So you can't "just" hang it in there. I never used sequalizer in this setup, but it makes sense. I found an article that shows the steps needed to incorporate it:
https://www.google.nl/amp/s/scotch.io/amp/tutorials/creating-an-angularjs-application-with-sequelize-part-1
Hope this helps you.