I'm using gulp to pack js. Also I wanna using other libraries like materializecss. So I'm just importing it in my main.js. But after builing gulp I faced an error:
events.js:165
throw er; // Unhandled 'error' event
^
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'
main.js
import "materialize-css";
const Vue = require("vue");
const $ = require("jquery");
const v = new Vue({
el: '#app',
ready: function () {
this.loadData();
},
data: {
message: 'Hfssfsfello Vue.13js!',
serverData: null
},
methods: {
loadData: function (viewerUserId, posterUserId) {
const that = this;
$.ajax({
contentType: "application/json",
dataType: "json",
url: window.ServerUrl + "/Home/GetData",
method: "GET",
success: function (response) {
console.log(response);
that.$data.serverData = response;
},
error: function () {
console.log("Oops");
}
});
}
}
})
gulpfile
const gulp = require('gulp');
const gutil = require('gulp-util');
var babel = require('gulp-babel');
var minify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
const fs = require('fs');
const path = require('path');
const browserify = require('browserify');
const watchify = require('watchify');
const fsPath = require('fs-path');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var es2015 = require('babel-preset-es2015');
function getFolders(dir) {
return fs.readdirSync(dir)
.filter(function (file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
const paths = [
process.env.INIT_CWD + '\\ViewModels\\home',
process.env.INIT_CWD + '\\ViewModels\\home\\components',
process.env.INIT_CWD + '\\ViewModels\\common\\components'
];
function watchFolder(input, output) {
var b = browserify({
entries: [input],
cache: {},
packageCache: {},
plugin: [watchify],
basedir: process.env.INIT_CWD,
paths: paths
});
function bundle() {
b.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(minify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(output));
gutil.log("Bundle rebuilt!");
}
b.on('update', bundle);
bundle();
}
function compileJS(input, output) {
// set up the browserify instance on a task basis
var b = browserify({
debug: true,
entries: [input],
basedir: process.env.INIT_CWD,
paths: paths
});
return b.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(babel({ compact: false, presets: ['es2015'] }))
// Add transformation tasks to the pipeline here.
.pipe(minify())
.on('error', gutil.log)
//.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(output));
}
const scriptsPath = 'ViewModels';
gulp.task('build', function () {
var folders = getFolders(scriptsPath);
gutil.log(folders);
folders.map(function (folder) {
compileJS(scriptsPath + "//" + folder + "//main.js", "Scripts//app//" + folder);
});
});
gulp.task('default', function () {
var folders = getFolders(scriptsPath);
gutil.log(folders);
folders.map(function (folder) {
watchFolder(scriptsPath + "//" + folder + "//main.js", "Scripts//app//" + folder);
});
});
By the way, I'm very new to vue js framework and I'm trying to integrate this framework with ASP .NET MVC. And I can't figure out what I'm doing wrong? I'd be very appreciated if somebody answers me.
Surely not an answer, but I refused to use gulp. Instead I've installed webpack. Now it's alright!
Related
In order to use MDX v2 with remark and rehype plugins in react applications created with Create React App v5 I have to use CRACO (v7) and especially its ability to handle a configuration that is returned as a promise/async function. The reason is that CRACO uses CJS module-based configuration, while the remark and rehype plugins are ES modules. Now I want to use MDXv2 with remark/rehype plugins in React Styleguidist too.
This is my craco.config.js:
const { addAfterLoader, loaderByName } = require('#craco/craco')
const mdxplagues = require('./mdxplugins.js')
// https://github.com/facebook/create-react-app/pull/11886#issuecomment-1055054685
const ForkTsCheckerWebpackPlugin =
process.env.TSC_COMPILE_ON_ERROR === 'true'
? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
: require('react-dev-utils/ForkTsCheckerWebpackPlugin');
module.exports = async (env) => {
const mdxplagueConfig = await mdxplagues()
return {
webpack: {
configure: (webpackConfig) => {
addAfterLoader(webpackConfig, loaderByName('babel-loader'), {
test: /\.(md|mdx)$/,
loader: require.resolve('#mdx-js/loader'),
/** #type {import('#mdx-js/loader').Options} */
options: mdxplagueConfig,
})
// https://github.com/facebook/create-react-app/pull/11886#issuecomment-1055054685
webpackConfig.plugins.forEach((plugin) => {
if (plugin instanceof ForkTsCheckerWebpackPlugin) {
plugin.options.issue.exclude.push({ file: '**/src/**/?(*.){spec,test,cy}.*' });
}
})
return webpackConfig
}
}
}
}
And this is my mdxplugins.js that returns an async function returing the needed plugin configurations:
const textrTypoEnDashes = (input) => {
return input
.replace(/ -- /gim, '–')
}
module.exports = async () => {
const remarkGfm = (await import('remark-gfm')).default
const remarkImages = (await import('remark-images')).default
const remarkTextr = (await import('remark-textr')).default
const remarkAccessibleEmoji = (await import('#fec/remark-a11y-emoji')).default
const rehypeSlug = (await import('rehype-slug')).default
const textrTypoApos = (await import('typographic-apostrophes')).default
const textrTypoQuotes = (await import('typographic-quotes')).default
const textrTypoPossPluralsApos = (await import('typographic-apostrophes-for-possessive-plurals')).default
const textrTypoEllipses = (await import('typographic-ellipses')).default
//const textrTypoEmDashes = (await import('typographic-em-dashes')).default
const textrTypoNumberEnDashes = (await import('typographic-en-dashes')).default
return {
remarkPlugins: [
remarkGfm,
remarkImages,
remarkAccessibleEmoji,
[remarkTextr, {
plugins: [
textrTypoApos,
textrTypoQuotes,
textrTypoPossPluralsApos,
textrTypoEllipses,
// textrTypoEmDashes,
textrTypoNumberEnDashes,
textrTypoEnDashes,
],
options: {
locale: 'en-us'
}
}],
],
rehypePlugins: [
rehypeSlug,
],
}
}
My problem is now that I need to apply this webpack/MDXv2 plugin configuration to styleguide.config.js (v13.0.0). I tried...
module.exports = async () => {
return {
...
}
}
...but this doesn't seem to be supported. A look into React Styleguidist's sources, namely scripts/config.ts seems to confirm this.
How can I synchronously resolve my MDX plugin configuration that I return via an async function from my mdxplugin.js CJS module within Styleguidist's CJS configuration module?
I'm learning how to write code of service worker and stuck with the error "ReferenceError: document is not defined" in my app.js file. I'm using workbox library with InjectManifest mode. I think the problem in the webpack.config.js, because when I delete InjectManifest in webpack.config.js the error disappears.
My webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const {InjectManifest} = require('workbox-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.html$/i,
use: [
{
loader: 'html-loader',
},
],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader, 'css-loader',
],
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
},
},
],
},
],
},
optimization: {
minimize: true,
minimizer: [
new CssMinimizerPlugin(),
],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
filename: './index.html',
}),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
new InjectManifest({
swSrc: './src/js/service.worker.js',
swDest: 'service.worker.js',
}),
],
};
My service.worker.js file:
import { precacheAndRoute } from 'workbox-precaching/precacheAndRoute';
import { cinemaNews } from './cinemaNews';
import { url } from './app';
precacheAndRoute(self.__WB_MANIFEST);
const CACHE_NAME = 'v1';
const responseCache = new Response(JSON.stringify(cinemaNews));
self.addEventListener('install', (evt) => {
console.log('install')
evt.waitUntil((async () => {
console.log('install waitUntil')
const cache = await caches.open(CACHE_NAME);
await cache.put(url, responseCache);
await self.skipWaiting();
})());
});
self.addEventListener('activate', (evt) => {
console.log('activate')
evt.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', (evt) => {
console.log('sw fetch')
const requestUrl = new URL(evt.request.url);
if (!requestUrl.pathname.startsWith('/news')) return;
evt.respondWith((async () => {
console.log('respondWith')
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(evt.request);
return cachedResponse;
})());
evt.waitUntil((async () => {
console.log('waitUntil');
const response = await fetch(evt.request.url);
const client = await clients.get(evt.clientId);
let json = await response.json();
client.postMessage(json);
})());
});
This statement:
import { url } from './app';
appears to be triggering the issue, as there must be code inside of your app.js that is executed via that import, and which assumes that document will be defined. (It's not defined inside of the ServiceWorkerGlobalScope.)
Based on how you're using the export, I'm assuming that it's just a string constant containing a shared URL that you want to use from both your main web app and your service worker. Assuming that's the case, the easiest thing to do would be to refactor your modules that there's a constants.js (or some similar name) module that only exports your string constants, and doesn't try to run any code that references document. You can then import the constant from either your web app or the service worker without issue.
// constants.js
export const url = '/path/to/url';
// service-worker.js
import {url} from './constants';
// do something with url
// app.js
import {url} from './constants';
// do something with url
I´m trying to copy files in gulp file dynamically based on json object.
I tried to use merge-stream package withou success.
const DEV_PATH = "./dev/";
const DIST_PATH = "./dist/";
const DEV_PATH_TOOLS = DEV_PATH + "tools/";
const DEV_PATH_COMMON = DEV_PATH + "common/";
const DIST_PATH_TOOLS = DIST_PATH + "tools/";
const TOOLS_DIST_PATH = [
{
"dir" : 'dir1',
"options" : {
"class" : [ "modules/csv/**/*" ]
}
},
{
"dir" : 'dir2',
"options" : {
"class" : [ "modules/csv/CsvImporter.php" ]
}
}
];
const gulp = require('gulp');
const plumber = require('gulp-plumber');
const merged = require('merge-stream')();
gulp.task( 'copy-class', function(){
TOOLS_DIST_PATH.map( t => function () {
var stream = new stream(
gulp.src( t.options.class.map( c => DEV_PATH_COMMON + c ))
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe( gulp.dest( DIST_PATH_TOOLS + t.dir + '/class' ) )
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
);
merged.add(stream);
});
return merged.isEmpty() ? null : merged;
});
gulp.task( 'default', gulp.series( 'copy-class' ) );
I got this error :
The following tasks did not complete: default, copy-class
Did you forget to signal async completion ?
It´s confused for me, someone can helps me ?
I found an answer
Const DEV_PATH = "./dev/";
const DIST_PATH = "./dist/";
const DEV_PATH_TOOLS = DEV_PATH + "tools/";
const DEV_PATH_COMMON = DEV_PATH + "common/";
const DIST_PATH_TOOLS = DIST_PATH + "tools/";
const TOOLS_DIST_PATH = [
{
"dir" : 'dir1',
"options" : {
"class" : [ "modules/csv/**/*" ]
}
},
{
"dir" : 'dir2',
"options" : {
"class" : [ "modules/csv/CsvImporter.php" ]
}
}
];
const gulp = require('gulp');
const plumber = require('gulp-plumber');
const merge= require('merge-stream');
function compileScripts(t) {
const classStream = gulp.src( t.options.class.map( c => DEV_PATH_COMMON + c ))
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe( gulp.dest( DIST_PATH_TOOLS + t.dir + '/class' ) )
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
/* TODO : when there wil be several options
return merge(classStream , otherStream );*/
return classStream;
}
gulp.task( 'copy-options', function(){
var streams = TOOLS_DIST_PATH.map( t => {
return compileScripts(t);
});
return merge(streams);
});
gulp.task( 'default', gulp.series( 'copy-options' ) );
Please help me if any body resolved the issue and below is my lambda funciton code.
when i comment all funcitons in exports.handler funciton and execute/test single function it is working but if we enable all funcitons then i am getting the error as Error handled: Cannot read property 'value' of undefined
Node JS code for alexa skill kit for different intents created.
GetNewFactHandler,
CreateJIRAIssueHandler,
UpdateJIRAIssueHandler,
GetJIRAIssueHandler,
GetJIRAIssueCountHandler,
/* eslint-disable func-names */
/* eslint-disable no-console */
var http = require('http');
var https = require('https');
var projectKey='';
var iType='';
var keyValueID='';
var userName='';
var IssueNumber='';
const Alexa = require('ask-sdk');
const GetNewFactHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest'
|| (request.type === 'IntentRequest'
&& request.intent.name === 'GetNewFactIntent');
},
handle(handlerInput) {
const factArr = data;
const factIndex = Math.floor(Math.random() * factArr.length);
const randomFact = factArr[factIndex];
const speechOutput = GET_FACT_MESSAGE + randomFact;
return handlerInput.responseBuilder
.speak(speechOutput)
.withSimpleCard(SKILL_NAME, randomFact)
.getResponse();
},
};
var reqTimeout = 3000;
const CreateJIRAIssueHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const proKey = request.intent.slots.PROJECTKEY.value;
const issueType = request.intent.slots.ISSUETYPE.value;
iType = capitalize_Words(issueType);
projectKey = proKey.toUpperCase();
return request.type === 'IntentRequest' &&
request.intent.name === 'CreateJIRAIssue';
},
async handle(handlerInput) {
const createIssue = await createJiraIssue(projectKey, iType);
const speechOutput = JSON.parse(createIssue).key;
return handlerInput.responseBuilder
.speak('Issue ' + speechOutput + ' created')
.getResponse();
},
};
function capitalize_Words(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
//mule real time server
var muleCreateIssuePath = '/jira/createissue';
var muleProtocol = 'https';
var createIssueMethod = 'POST';
var muleUpdateIssuePath = '/jira/issue/';
var updateIssueMethod = 'PUT';
var getIssueMethod = 'GET';
var MuleReqOpts = {
host: '',
port: 443,
path: undefined, // To be set.
method: undefined,
headers: {
'Content-Type': 'application/json'
},
agent: false,
// auth: jiraUsername + ':' + jiraPassword
auth: ''
};
var MuleHttp = muleProtocol === 'https' ? https : http;
function createJiraIssue(projectKey, iType) {
MuleReqOpts.path = muleCreateIssuePath;
MuleReqOpts.method = createIssueMethod;
var MuleReqBody = {
'fields': {
'project': {
'key': projectKey
},
'summary': 'Test Message',
'description': 'Issue created for alexa skill kit from Integration alexa to jira',
'issuetype': {
'name': iType // Make sure your JIRA project configuration(s) supports this Issue Type.
}
}
};
return doApiCall(MuleHttp, MuleReqOpts, MuleReqBody, 'creating issue', 201);
};
function doApiCall(httplib, reqOpts, reqBody, happening, successCode) {
return new Promise(((resolve, reject) => {
var req = httplib.request(reqOpts, (res) => {
res.setEncoding('utf8');
let returnData = '';
res.on('data', (chunk) => {
returnData += chunk;
});
res.on('end', () => {
resolve(returnData);
});
res.on('error', (error) => {
reject(error);
});
});
req.write(JSON.stringify(reqBody));
req.end();
req.on('error', function(err) {
context.done(new Error(' request error: ' + err.message));
});
req.setTimeout(reqTimeout, function() {
context.done(new Error(' request timeout after ' + reqTimeout + ' milliseconds.'));
});
}));
};
const UpdateJIRAIssueHandler = {
canHandle(handlerInput) {
console.log('1');
const request = handlerInput.requestEnvelope.request;
console.log('2');
userName = request.intent.slots.USER.value;
var keyValue = request.intent.slots.PROJECTKEY.value;
console.log('keyValue : ' + keyValue);
keyValueID = keyValue.toUpperCase();
IssueNumber = request.intent.slots.ISSUENUMBER.value;
let INumber = Number(IssueNumber);
console.log('IssueNumber value: '+INumber);
console.log('key value id: ' + keyValueID);
return request.type === 'IntentRequest' &&
request.intent.name === 'UpdateJIRAIssue';
},
async handle(handlerInput) {
const updateIssue = await updateJiraIssue(userName);
console.log('updateIssue log: ' + updateIssue);
const speechOutput = JSON.parse(updateIssue).responseMessage;
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function updateJiraIssue(userName) {
console.log('inside method: ' +userName);
MuleReqOpts.method = updateIssueMethod;
var postdata = {
"fields": {
"assignee": {
"name": userName
}
}
}
return doApiUpdateCall(MuleHttp, MuleReqOpts, postdata, 'updating issue', 201);
};
function doApiUpdateCall(httplib, options, postdata, happening, successCode) {
options.path = muleUpdateIssuePath + keyValueID +'-'+IssueNumber ;
return new Promise(((resolve, reject) => {
var req = httplib.request(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log(returnData);
});
res.on('end', () => {
resolve(returnData);
});
console.log('1');
console.log('Body: ');
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
var jirapostString = JSON.stringify(postdata);
console.log(jirapostString);
req.write(jirapostString);
req.end();
}));
};
const GetJIRAIssueHandler = {
canHandle(handlerInput) {
console.log('1');
const request = handlerInput.requestEnvelope.request;
var keyValue = request.intent.slots.Issue.value;
console.log('keyValue: ' + keyValue);
keyValueID = keyValue.toUpperCase();
return request.type === 'IntentRequest' &&
request.intent.name === 'GetJIRAIssue';
},
async handle(handlerInput) {
const getIssue = await GetJIRAIssue();
console.log('getIssue log: ' + getIssue);
const assigneeName = JSON.parse(getIssue).fields.assignee.name;
const key = JSON.parse(getIssue).fields.assignee.key;
const reporterName = JSON.parse(getIssue).fields.reporter.name;
const issueType = JSON.parse(getIssue).fields.issuetype.name;
const projectName = JSON.parse(getIssue).fields.project.name;
const summaryDetails = JSON.parse(getIssue).fields.summary;
const speechOutput = 'Here are the issue details summary: Assignee : ' + assigneeName.concat(' ,reporter : ' + reporterName, ' ,Issue Key : ' + key, ' ,IssueType : ' + issueType, ' ,ProjectName : ' + projectName, ' ,Summary : ' + summaryDetails);
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function GetJIRAIssue() {
MuleReqOpts.method = getIssueMethod;
return doApiGetIssueCall(MuleHttp, MuleReqOpts, 'get issue details', 201);
};
function doApiGetIssueCall(httplib, options, happening, successCode) {
options.path = muleUpdateIssuePath + keyValueID;
return new Promise(((resolve, reject) => {
https.get(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log('response :', returnData);
});
res.on('end', () => {
resolve(returnData);
});
});
}));
};
const GetJIRAIssueCountHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
userName = request.intent.slots.USER.value;
console.log('userName Value: ' + userName);
const issueType = request.intent.slots.ISSUETYPE.value;
iType = capitalize_Words(issueType);
return request.type === 'IntentRequest' &&
request.intent.name === 'GetJIRAIssueCount';
},
async handle(handlerInput) {
const getIssueCount = await GetJIRAIssueCount();
console.log('getIssue log: ' + getIssueCount);
const total = JSON.parse(getIssueCount).total;
const speechOutput = ('Here is the '+iType+' count details: ' +total );
console.log('speechOutput log: ' + speechOutput);
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
function GetJIRAIssueCount() {
MuleReqOpts.method = getIssueMethod;
return doApiGetIssueCountCall(MuleHttp, MuleReqOpts, 'get issue count details', 201);
};
function doApiGetIssueCountCall(httplib, options, happening, successCode) {
options.path = muleUpdateIssuePath + userName +'/'+iType;
return new Promise(((resolve, reject) => {
https.get(options, (res) => {
console.log(options);
res.setEncoding('utf8');
let returnData = '';
res.on('data', (body) => {
returnData += body;
console.log('response :', returnData);
});
res.on('end', () => {
resolve(returnData);
});
});
}));
};
const HelpHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& request.intent.name === 'AMAZON.HelpIntent';
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(HELP_MESSAGE)
.reprompt(HELP_REPROMPT)
.getResponse();
},
};
const ExitHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& (request.intent.name === 'AMAZON.CancelIntent'
|| request.intent.name === 'AMAZON.StopIntent');
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(STOP_MESSAGE)
.getResponse();
},
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
return handlerInput.responseBuilder.getResponse();
},
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.log(`Error handled: ${error.message}`);
return handlerInput.responseBuilder
.speak('Sorry, an error occurred.')
.reprompt('Sorry, an error occurred.')
.getResponse();
},
};
const SKILL_NAME = 'Space Facts';
const GET_FACT_MESSAGE = 'Here\'s your fact: ';
const HELP_MESSAGE = 'You can say tell me a space fact, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';
const data = [
'A year on Mercury is just 88 days long.',
'Despite being farther from the Sun, Venus experiences higher temperatures than Mercury.',
'Venus rotates counter-clockwise, possibly because of a collision in the past with an asteroid.',
'On Mars, the Sun appears about half the size as it does on Earth.',
'Earth is the only planet not named after a god.',
'Jupiter has the shortest day of all the planets.',
'The Milky Way galaxy will collide with the Andromeda Galaxy in about 5 billion years.',
'The Sun contains 99.86% of the mass in the Solar System.',
'The Sun is an almost perfect sphere.',
'A total solar eclipse can happen once every 1 to 2 years. This makes them a rare event.',
'Saturn radiates two and a half times more energy into space than it receives from the sun.',
'The temperature inside the Sun can reach 15 million degrees Celsius.',
'The Moon is moving approximately 3.8 cm away from our planet every year.',
];
const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
.addRequestHandlers(
GetNewFactHandler,
CreateJIRAIssueHandler,
UpdateJIRAIssueHandler,
GetJIRAIssueHandler,
GetJIRAIssueCountHandler,
HelpHandler,
ExitHandler,
SessionEndedRequestHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();
Check all of your code for instances where you are looking for someObject.someNestedProperty.value.
I suspect that your slot values in your Intents are not the same as defined in your model/some-LANG.json file. Trying to access value property from someObject without a someNestedProperty will cause your error (i.e. request.intent.slots.PROJECTKEY.value).
If this is a Alexa-hosted skill, CloudWatch logging is built right in. Open the Alexa Developer Console, edit your skill, then go to the Code tab. On the bottom left, you should see a link for Logs: Amazon CloudWatch. You can log anything you want with a simple console.log() statement.
Also, be aware that the ask-sdk-core npm package contains helper methods to get slotValues (among other great tools). For more information, see this link: https://developer.amazon.com/en-US/docs/alexa/alexa-skills-kit-sdk-for-nodejs/utilities.html
Thanks all for your suggestions and prompt response.
Now the issue is resolved and the solution is the addRequestHandlers method will execute methods sequentially even if you execute/trigger third handler it will execute 1st and 2nd and goes to 3rd one. Here the issue is when you trigger a 3rd handler command from alexa it will passs the slot values related to the 3rd handler utterance and hence the 1st and 2nd haldler having slot values are not able to resolve and failed. so i put a condition overthere to skip 1st and 2nd handler execution and it worked.
I'm trying to create a yeoman generator to speed up some process of mine,
but there are some issues doing so.
The input of the name is the value true, instead of the value provided
When not all values are provided I get a confirm, but after that nothing else happens (only when all arguments are provided)
the scaffoldFolders isn't creating the folders (EDIT: got that working)
does anyone know any (or even better: all) solutions to my problem?
here is the index.js I'm using:
'use strict';
var Generator = require('yeoman-generator');
var util = require('util')
var OptionOrPrompt = require('yeoman-option-or-prompt');
var mkdirp = require('mkdirp');
var _ = require('underscore.string');
var GlatGenerator = class extends Generator {
constructor(args, opts) {
// Calling the super constructor is important so our generator is correctly set up
super(args, opts);
this._optionOrPrompt = OptionOrPrompt;
this.props = {};
}
prompting() {
var done = this.async();
// Instead of calling prompt, call _optionOrPrompt to allow parameters to be passed as command line or composeWith options.
this._optionOrPrompt([{
type: 'input',
name: 'name',
message: 'Your component name',
default: 'hoogwerker',
store: true
}, {
type: 'confirm',
name: 'model',
message: 'Should we create a model for you?',
default: true,
store: true
}, {
type: 'confirm',
name: 'service',
message: 'Should we create a service for you?',
default: true,
store: true
}], function (answers) {
this.props.componentName = answers.name
this.props.createModel = answers.model
this.props.createService = answers.service
console.log("**********************");
console.log("***" + (JSON.stringify(answers)));
console.log("**********************");
done();
}.bind(this));
}
scaffoldFolders() {
console.log('scaffoldFolders');
var slugify = _.slugify(this.props.componentName);
var classify = _.classify(this.props.componentName);
var lowerName = _.decapitalize(_.classify(this.props.componentName));
mkdirp("src/components/" + lowerName);
mkdirp("src/components/" + lowerName + "/components");
if (this.props.createModel) {
mkdirp("src/components/" + lowerName + "/models");
}
if (this.props.createModel) {
mkdirp("src/components/" + lowerName + "/services");
}
}
copyMainFiles() {
console.log('copyMainFiles');
var slugify = _.slugify(this.props.componentName);
var classify = _.classify(this.props.componentName);
var lowerName = _.decapitalize(classify);
var dash = _.dasherize(lowerName);
var context = {
component_name: slugify,
component_name_camel: classify,
component_name_lower: lowerName,
component_name_dash: dash,
};
var base = "src/components/" + lowerName + "/";
this.fs.copyTpl(
this.templatePath('base-files/_component.html'),
this.destinationPath(base + lowerName + ".component.html"),
context
);
this.fs.copyTpl(
this.templatePath('base-files/_component.scss'),
this.destinationPath(base + lowerName + ".component.scss"),
context
);
this.fs.copyTpl(
this.templatePath('base-files/_component.ts'),
this.destinationPath(base + lowerName + ".component.ts"),
context
);
this.fs.copyTpl(
this.templatePath('base-files/_module.ts'),
this.destinationPath(base + lowerName + ".module.ts"),
context
);
this.fs.copyTpl(
this.templatePath('base-files/_routes.ts'),
this.destinationPath(base + lowerName + ".routes.ts"),
context
);
if (this.props.createModel) {
this.fs.copyTpl(
this.templatePath('model/_model.ts'),
this.destinationPath(base + "/models/" + classify + ".ts"),
context
);
}
if (this.props.createService) {
this.fs.copyTpl(
this.templatePath('service/_service.ts'),
this.destinationPath(base + "/services/" + lowerName + ".service.ts"),
context
);
}
}
};
module.exports = GlatGenerator;
// module.exports = base.extend({
// initializing: () => {},
// prompting: () => {},
// configuring: () => {},
// default: () => {},
// writing: () => {},
// conflicts: () => {},
// install: () => {},
// end: () => {}
// });
and the command used:
yo glat:component --name="hoogwerker" --model --service
--name is being parsed as a Boolean. You need to specify the type as a string. this.option('name', {type: String})
For the second point, it's hard to help you without seeing _optionOrPrompt function. But it looks like a bug on your side, the function doesn't trigger the callback when all values are passed as options.