I am getting this error for the past hours and i have not been able to resolve it. I have tried all the solutions online including uninstalling aslant globally and in the project and installing it again. Unfortunately the most common answer does not really apply in my case since my package.json file does not really have that file structure.
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint .
/Users/KingdomMac/Downloads/ermnl-dashboard-master/functions/index.js
22:71 error Parsing error: Unexpected token =>
✖ 1 problem (1 error, 0 warnings)
Error: functions predeploy error: Command terminated with non-zero exit code1
My package.json file
{
"name": "vue-white-dashboard",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.35",
"#fortawesome/free-brands-svg-icons": "^5.15.3",
"#fortawesome/free-regular-svg-icons": "^5.15.3",
"#fortawesome/free-solid-svg-icons": "^5.15.3",
"#fortawesome/vue-fontawesome": "^2.0.2",
"axios": "^0.21.1",
"chart.js": "^2.8.0",
"core-js": "^2.6.5",
"firebase": "^8.6.8",
"node-sass": "^4.9.0",
"vue": "^2.6.10",
"vue-chartjs": "^3.4.2",
"vue-click-outside": "^1.0.7",
"vue-clickaway": "^2.2.2",
"vue-github-buttons": "^3.1.0",
"vue-i18n": "^8.14.1",
"vue-router": "^3.0.3",
"vue-social-sharing": "^2.4.6",
"vue2-transitions": "^0.3.0",
"vuetify": "^2.4.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^3.11.0",
"#vue/cli-plugin-eslint": "^3.1.1",
"#vue/cli-service": "^3.5.3",
"#vue/eslint-config-prettier": "^5.0.0",
"babel-eslint": "^10.0.1",
"eslint": "^8.1.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-vue": "^7.20.0",
"prettier": "^1.18.2",
"sass": "~1.32",
"sass-loader": "^10.0.0",
"vue-cli-plugin-vuetify": "~2.4.1",
"vue-template-compiler": "^2.6.10",
"vuetify-loader": "^1.7.0"
}
}
Also my .eslintrc.js file
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "plugin:vue/essential",
"parserOptions": {
"ecmaVersion": 13
},
"plugins": [
"vue"
],
"rules": {
}
};
And my index.js file
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
// exports.addAdminRole = functions.https.onCall((data, context) => {
// // Get user and add custom claim (admin)
// const customClaims = {
// admin: true,
// };
// return admin.auth().getUserByEmail(data.email).then((user) => {
// return admin.auth().setCustomUserClaims(user.uid, customClaims);
// }).then((authUser) => {
// return {
// message: `Success! ${data.email} has been made an admin.`,
// };
// }).catch((error) => {
// return error;
// });
// });
exports.addUserRole = functions.auth.user().onCreate(async (authUser) => {
if (authUser.email) {
const customClaims = {
admin: true,
};
try {
let _ = await admin.auth().setCustomUserClaims(authUser.uid, customClaims);
return db.collection("roles").doc(authUser.uid).set({
email: authUser.email,
role: customClaims,
});
} catch (error) {
console.log(error);
}
}
});
exports.setUserRole = functions.https.onCall(async (data, context) => {
if (!context.auth.token.admin) return
try {
let _ = await admin.auth().setCustomUserClaims(data.uid, data.role)
return db.collection("roles").doc(data.uid).update({
role: data.role
})
} catch (error) {
console.log(error)
}
});
try changing "lint": "eslint ." to "lint": "eslint ", in your package.json
Related
I've a project with (next 12.1.6 + react 18.1 + react-dom 18.1). Now i want to add React Server Components to it. Updated my next.config.js like this
const nextConfig = {
distDir: '../../.next',
reactStrictMode: true,
experimental: {
runtime: 'nodejs',
serverComponents: true,
concurrentFeatures: true,
},
};
module.exports = nextConfig;
But regardless of that, when i execute npm run start:dev (npm run build works fine i believe) i get the error:
Error: `experimental.runtime` requires `experimental.reactRoot` to be enabled along with React 18. at Object.getBaseWebpackConfig [as default] (G:\ORLVNIcard\orlvni-business-card\node_modules\next\build\webpack-config.ts:355:11) at async Promise.all (index 0) at Span.traceAsyncFn (G:\ORLVNIcard\orlvni-business-card\node_modules\next\trace\trace.ts:106:14) at Span.traceAsyncFn (G:\ORLVNIcard\orlvni-business-card\node_modules\next\trace\trace.ts:106:14) at HotReloader.start (G:\ORLVNIcard\orlvni-business-card\node_modules\next\server\dev\hot-reloader.ts:518:21) at DevServer.prepare (G:\ORLVNIcard\orlvni-business-card\node_modules\next\server\dev\next-dev-server.ts:404:5) at ViewService.onModuleInit (G:\ORLVNIcard\orlvni-business-card\src\server\view\view.service.ts:19:7) at async Promise.all (index 0) at Object.callModuleInitHook (G:\ORLVNIcard\orlvni-business-card\node_modules\#nestjs\core\hooks\on-module-init.hook.js:43:5) at NestApplication.callInitHook (G:\ORLVNIcard\orlvni-business-card\node_modules\#nestjs\core\nest-application-context.js:169:13)
Next.js documentation says in https://nextjs.org/docs/advanced-features/react-18/server-components that i should use next#canary instead of next#12.1.6, and it works, but i have another problem with #canary in HookWebpackError: The "to" argument must be of type string. Received undefined and #12.1.6 does not throw the error in fresh barely empty project with (next 12.1.6 + react 18.1 + react-dom 18.1).
Part of my package.json looks like this
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build && cd src/client && next build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "^8.0.0",
"#nestjs/config": "^1.1.5",
"#nestjs/core": "^8.0.0",
"#nestjs/jwt": "^8.0.0",
"#nestjs/mongoose": "^9.0.2",
"#nestjs/passport": "^8.0.1",
"#nestjs/platform-express": "^8.0.0",
"#types/bcrypt": "^5.0.0",
"#types/mongoose": "^5.11.97",
"bcrypt": "^5.0.1",
"cookie-parser": "^1.4.6",
"dotenv": "^10.0.0",
"mongodb": "^4.3.1",
"mongoose": "^6.1.10",
"mssql": "^7.3.0",
"next": "^12.1.6",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"react": "18.1.0",
"react-dom": "18.1.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"sass": "^1.45.0",
"ts-node": "^10.0.0"
},
"devDependencies": {
"#nestjs/cli": "^8.0.0",
"#nestjs/schematics": "^8.0.0",
"#nestjs/testing": "^8.0.0",
"#types/cookie-parser": "^1.4.2",
"#types/express": "^4.17.13",
"#types/jest": "27.0.2",
"#types/node": "^16.0.0",
"#types/passport-jwt": "^3.0.6",
"#types/react": "^18.0.12",
"#types/react-dom": "^18.0.5",
"#types/supertest": "^2.0.11",
"#typescript-eslint/eslint-plugin": "^5.0.0",
"#typescript-eslint/parser": "^5.0.0",
"eslint": "^7.28.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "^27.2.5",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^3.10.1",
"typescript": "^4.3.5"
},
And this is how i start my next app
import { Injectable, OnModuleInit } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import createServer from 'next';
import { NextServer } from 'next/dist/server/next';
import { Request, Response } from 'express';
#Injectable()
export class ViewService implements OnModuleInit {
private server: NextServer;
constructor(private configService: ConfigService) {}
async onModuleInit(): Promise<void> {
try {
this.server = createServer({
dev: this.configService.get<string>('NODE_ENV') !== 'production',
dir: './src/client',
});
await this.server.prepare();
} catch (error) {
console.error(error);
}
}
handler(req: Request, res: Response) {
return this.server.getRequestHandler()(req, res);
}
}
Guess the error is due to next somehow not seeing react 18 in #12.1.6, but i can't realize why, especially while in new project everything works fine.
Remove your package-lock.json and install the canary version of next
npm install next#canary react#latest react-dom#latest
Then add expermiental settings in your next.config.js
experimental: {
reactRoot: true,
runtime: "nodejs",
serverComponents: true,
concurrentFeatures: true
}
Apparently the error was thrown 'cause by default createServer() method of Next.js is creating react server with react 17 and old methods of react, like render(), hydrate() and so on. To make createServer() create react 18 server it's necessary to define __NEXT_REACT_ROOT as true in the environment of the process of our custom server. At least i've understood it this way. So the solution is
async onModuleInit(): Promise<void> {
process.env.__NEXT_REACT_ROOT = 'true';
try {
this.server = createServer({
dev: this.configService.get<string>('NODE_ENV') !== 'production',
dir: './src/client',
});
await this.server.prepare();
} catch (error) {
console.error(error);
}
}
It solved the problem for me.
Just add this line to your .env file and it will fix the issue
__NEXT_REACT_ROOT=true
I'm using vue cli and builded electron inside. Here is my package.json
{
"name": "rule-the-world",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"electron:build": "vue-cli-service electron:build",
"electron:serve": "vue-cli-service electron:serve",
"postinstall": "electron-builder install-app-deps",
"postuninstall": "electron-builder install-app-deps"
},
"main": "background.js",
"dependencies": {
"core-js": "^3.6.5",
"fs": "^0.0.1-security",
"globe.gl": "^2.23.0",
"json-loader": "^0.5.7",
"register-service-worker": "^1.7.1",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-plugin-pwa": "~4.5.0",
"#vue/cli-plugin-router": "~4.5.0",
"#vue/cli-plugin-vuex": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"electron": "^16.0.5",
"electron-devtools-installer": "^3.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0",
"sass": "^1.26.5",
"sass-loader": "^8.0.2",
"vue-cli-plugin-electron-builder": "~2.1.1"
}
}
and when I try to use fs in electron window I got an error like "Uncaught (in promise) TypeError: fs.readdirSync", here is my code
const fs = require('fs')
function getFiles(__dirname) {
let filenames = fs.readdirSync(__dirname);
let files = [];
filenames.forEach((file) => {
let _file = new Object();
let data = fs.readFileSync(`${__dirname}/${file}`, {
encoding: "utf8",
flag: "r",
});
let parseData = JSON.parse(data);
_file.name = parseData.name;
_file.folderName = file;
_file.saveDate = parseData.saveDate;
_file.player = new Object();
_file.player.name = parseData.result.inGame.player.name;
_file.player.familyName = parseData.result.inGame.player.familyName;
_file.player.flag = parseData.result.inGame.player.flag;
_file.player.culture = parseData.result.inGame.player.family.culture;
files.push(_file);
});
// Display the file data
return files;
}
And this code was working few months ago, I don't remember what did I changed lastly or did I. It's basically getting save files system for my electron,vue game. I look for a lot of solutions but couldn't find one to work, anyone knew this?
I would like to write tests for my Node/Express/Typescript application. Next to my src directory I added a tests directory with a app.spec.ts file with this demo content
import { App } from '../src/app';
describe('App', () => {
let instance: App;
beforeEach(() => {
instance = new App();
});
it('creates an instance of App', async () => {
expect(instance).toBeInstanceOf(App);
});
});
Unfortunately Jest is not able to handle Typescript.
Details:
C:...\tests\app.spec.ts:1
({"Object.
":function(module,exports,require,__dirname,__filename,global,jest){import
{ App } from '../src/app';
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
This is my package.json (relavant fields)
{
"scripts": {
"start": "node dist/app.js",
"dev": "nodemon src/app.ts",
"build": "tsc -p .",
"test": "jest",
"testWithCoverage": "jest --coverage"
},
"devDependencies": {
"#types/express": "^4.17.0",
"#types/jest": "^24.0.17",
"#types/node": "^12.6.9",
"#typescript-eslint/eslint-plugin": "^1.13.0",
"#typescript-eslint/parser": "^1.13.0",
"eslint": "^5.16.0",
"eslint-config-airbnb-base": "^13.2.0",
"eslint-plugin-import": "^2.18.2",
"jest": "^24.8.0",
"nodemon": "^1.19.1",
"ts-jest": "^24.0.2",
"ts-node": "^8.3.0",
"typescript": "^3.5.3"
}
}
Further I created a jest.config.js file with that content
module.exports = {
roots: [
'./tests',
],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx',
],
};
Does someone know what's missing here?
Change your jest.config.js file to:
module.exports = {
"roots": [
"<rootDir>/src",
"<rootDir>/tests"
],
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
}
I am trying to develop a custom reporter for mocha output that will be used with protractor. I have developed a good deal of the reporter and if I use the "--reporter" command line argument it works fine. However if I try to specify it in mocharc, or more importantly reporterOptions within the protractor configuration file it can't seem to find the package. Is the command line reporter flag the only way to specify a local/custom reporter? If not, how are you supposed to specify it outside of the command line?
.babelrc:
require:
- '#babel/polyfill'
- '#babel/register'
reporter: './mocha-reporter'
spec: '_src/js/tests/unit/**/*.spec.js'
package.json:
{
"name": "box",
"version": "1.0.0",
"description": "boom!",
"main": "index.js",
"scripts": {
"mocha": "mocha",
"mocha-custom": "mocha -O outputDir=_src/js/tests/reports,testDir=_src/js/tests/unit --reporter mocha-reporter",
"mochawesonme": "mocha --reporter mochawesome --reporter-options reportDir=_src/js/tests/reports,reportFilename=PCMS_unit_test_results",
"check-types": "tsc",
"clean-selenium": "webdriver-manager clean",
"update-selenium": "webdriver-manager update --standalone --versions.standalone=3.8.0",
"start-selenium": "webdriver-manager start --versions.standalone=3.8.0",
"integration-tests": "protractor protractor.conf.js"
},
"devDependencies": {
"#babel/cli": "~7.4.3",
"#babel/core": "~7.4.3",
"#babel/plugin-proposal-class-properties": "7.4.0",
"#babel/plugin-proposal-object-rest-spread": "~7.4.3",
"#babel/plugin-transform-destructuring": "~7.4.3",
"#babel/polyfill": "~7.4.3",
"#babel/preset-env": "~7.4.3",
"#babel/preset-typescript": "~7.3.3",
"#babel/register": "~7.4.0",
"#fortawesome/fontawesome-free": "5.8.1",
"#types/bluebird": "3.5.26",
"#types/jquery": "3.3.29",
"#types/knockout": "~3.4.65",
"#typescript-eslint/eslint-plugin": "~1.7.0",
"#typescript-eslint/parser": "~1.7.0",
"appcache-webpack-plugin": "~1.4.0",
"autoprefixer": "~9.5.1",
"babel-loader": "~8.0.5",
"chai": "~4.2.0",
"chai-as-promised": "7.1.1",
"copy-webpack-plugin": "~5.0.3",
"css-loader": "~2.1.1",
"eslint": "~5.16.0",
"eslint-config-airbnb-base": "~13.1.0",
"eslint-config-airbnb-typescript": "~3.0.0",
"eslint-plugin-import": "~2.17.2",
"file-loader": "~3.0.1",
"html-loader": "~0.5.5",
"html-webpack-plugin": "3.2.0",
"js-yaml": "~3.13.1",
"json-loader": "~0.5.7",
"jszip": "~3.2.1",
"karma": "~4.1.0",
"karma-chai": "~0.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-firefox-launcher": "~1.1.0",
"karma-mocha": "~1.3.0",
"karma-sinon": "~1.0.5",
"karma-webpack": "~3.0.5",
"mini-css-extract-plugin": "~0.6.0",
"mocha": "~6.1.4",
"mocha-reporter": "file:mocha-reporter",
"mochawesome": "~3.1.2",
"mochawesome-report-generator": "3.1.5",
"mochawesome-screenshots": "1.6.0",
"node-sass": "^4.12.0",
"popper.js": "~1.15.0",
"postcss-loader": "~3.0.0",
"protractor": "5.4.2",
"protractor-image-comparison": "3.1.0",
"sass-loader": "~7.1.0",
"sinon": "~7.3.2",
"style-loader": "~0.23.1",
"typescript": "~3.4.5",
"url-loader": "~1.1.2",
"webpack": "~4.30.0",
"webpack-cli": "~3.3.1",
"webpack-dev-server": "~3.3.1"
},
"dependencies": {
"bluebird": "~3.5.4",
"bootstrap": "3.3.7",
"d3": "~5.9.2",
"isomorphic-fetch": "2.2.1",
"jquery": "^3.4.0",
"jquery-ui": "~1.12.1",
"knockout": "~3.5.0",
"knockout-mapping": "~2.6.0",
"lodash": "~4.17.11",
"numeral": "~2.0.6",
"page": "~1.11.4"
}
}
index.js:
import mochaBaseReporter from 'mocha/lib/reporters/base';
import { takeScreenShot } from './javascript/screenShots';
import { populateTestResults } from './javascript/testTree';
import {
getFileContents,
writeToOutputFile,
} from './javascript/fileSystemAccess';
import {
getTemplate,
parseTestsIntoOutput,
addValuesToTemplate,
} from './javascript/templating';
import {
SUCCESS,
FAILURE,
FINISHED,
} from './constants';
const addStyle = template => getFileContents('styles.css')
.then(styles => addValuesToTemplate(template, { styles }))
.catch(error => console.log('file read of styles.css failed', error));
const createReport = (outputDirectory, fileName, data) => getTemplate('report')
.then(template => addValuesToTemplate(template, { 'test-suites': data }))
.then(template => writeToOutputFile(outputDirectory, `${fileName}.html`, template))
.catch(error => console.log('file read of template.html failed', error));
function mochaReporter(runner, environment) {
const tests = {};
const fileName = 'testfile';
const { outputDir, testDir, takeScreenShotOnFailure } = environment.reporterOptions || {};
const outputDirectory = outputDir && `${process.cwd()}/${outputDir}`;
const accumulateTestResults = (test, image) => populateTestResults(test, testDir, tests, image);
mochaBaseReporter.call(this, runner);
runner.on(SUCCESS, accumulateTestResults);
runner.on(FAILURE, test => (
takeScreenShotOnFailure && window
? takeScreenShot()
: Promise.resolve()
).then(image => accumulateTestResults(test, image)));
runner.on(FINISHED, () => {
parseTestsIntoOutput(tests)
.then(addStyle)
.then(template => addValuesToTemplate(template, runner.stats))
.then(html => createReport(outputDirectory, fileName, html))
.then(() => writeToOutputFile(
`${outputDirectory}/history`,
`test-run-${Date.now()}.json`,
JSON.stringify(tests),
));
});
return runner;
}
module.exports = mochaReporter;
protractor.conf:
/* eslint-disable global-require */
/* eslint-disable #typescript-eslint/no-var-requires */
const protractor = require('protractor');
const { join } = require('path');
const testDirectory = '_src/js/tests';
const baseDirectory = `${testDirectory}/integration/`;
// specifies whether tests will be run in parralel or not
const shardTestFiles = true;
// specifies how many browsers/drivers may be run in parralel
const maxInstances = 4;
function onPrepare() {
// register typescript file extensions with the babel compiler
require('#babel/register')({ extensions: ['.js', '.ts'] });
require('#babel/polyfill');
// don't wait for angular (since our app is currently not angular)
protractor.browser.waitForAngularEnabled(false);
// hot fix for protractor strange map behavior
// found here: https://github.com/angular/protractor/issues/2227#issuecomment-337249891
protractor.ElementArrayFinder.prototype.map = function mapHotFix(mapFn) {
return this.reduce((arr, el) => arr.concat(mapFn(el, arr.length)), []);
};
}
exports.config = {
// mocha configuration
framework: 'mocha',
mochaOpts: {
reporter: './mocha-reporter',
reporterOptions: {
outputDir: `${testDirectory}/reports`,
testDir: `${baseDirectory}/endToEnd`,
takeScreenShotOnFailure: true,
},
timeout: 600000,
slow: 3000,
},
seleniumAddress: 'http://localhost:4444/wd/hub',
// turn off promise management in favor of async/await
SELENIUM_PROMISE_MANAGER: false,
// spec config
specs: [`${baseDirectory}/endToEnd/**/*.spec.js`],
// browser configuration
timeout: 100000,
multiCapabilities: [
{
browserName: 'chrome',
shardTestFiles,
maxInstances,
chromeOptions: {
args: [
// 'show-fps-counter=true',
'--headless',
// '--disable-gpu',
'--window-size=1300,1000',
],
},
},
{
browserName: 'firefox',
shardTestFiles,
maxInstances,
'moz:firefoxOptions': {
args: [
'--headless',
],
},
},
],
onPrepare,
plugins: [
{
package: 'protractor-image-comparison',
options: {
baselineFolder: join(process.cwd(), `${baseDirectory}/screenshots/baseline/`),
screenshotPath: join(process.cwd(), `${baseDirectory}/screenshots/tmp/`),
formatImageName: '{tag}-{logName}-{width}x{height}',
savePerInstance: true,
autoSaveBaseline: true,
},
},
],
};
I could not find a way to load the local file directly, however I gave it a package.json and installed it directly to node_modules with npm. To be specific I ran
npm install ./mocha-reporter --save-dev
on my project directory after creating a package.json within the project folder. After some debugging I was able to solve my issue since the package was now a part of node's named packages.
I am using this code to update an image and get the URL, but I can´t get the URL back.
It seems that return some because it can enter in the return of the promise.
I get this code from here: https://gist.github.com/CristalT/2651023cfa2f36cddd119fd979581893
The code work for another user so I this the problems would be in the dependence or in the database rules.
I am authenticated.
<template>
<div>
<input type="file" multiple accept="image/*" #change="detectFiles($event.target.files)">
<div class="progress-bar" :style="{ width: progressUpload + '%'}">{{ progressUpload }}%</div>
</div>
</template>
<script>
import { storage } from '../firebase'
export default {
data () {
return {
progressUpload: 0,
file: File,
uploadTask: '',
downloadURL: ''
}
},
methods: {
detectFiles (fileList) {
Array.from(Array(fileList.length).keys()).map( x => {
this.upload(fileList[x])
})
},
upload (file) {
this.uploadTask = storage.ref('imagenes/articulos').put(file);
this.uploadTask.then(snapshot => {
this.downloadURL = this.uploadTask.snapshot.downloadURL;
this.$emit('url', this.downloadURL)
})
}
},
watch: {
uploadTask: function() {
this.uploadTask.on('state_changed', sp => {
this.progressUpload = Math.floor(sp.bytesTransferred / sp.totalBytes * 100)
})
}
}
}
</script>
<style>
.progress-bar {
margin: 10px 0;
}
</style>
this is my package.json:
{
"name": "vue-change-your-home",
"version": "1.0.0",
"description": "Single page make in vue",
"author": "enrikiko <enrikiko_91#hotmail.com>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"build": "node build/build.js"
},
"dependencies": {
"#fortawesome/fontawesome": "^1.1.8",
"#fortawesome/fontawesome-free-solid": "^5.0.13",
"#fortawesome/vue-fontawesome": "0.0.22",
"bootstrap-vue": "^2.0.0-rc.9",
"firebase": "^5.0.2",
"vue": "^2.5.2",
"vue-router": "^3.0.1",
"vuefire": "^1.4.5"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"chalk": "^2.0.1",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^2.30.1",
"node-notifier": "^5.1.2",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-loader": "^13.3.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"webpack": "^3.6.0",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-server": "^2.9.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
this are the storage rules:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
this is my firebase.js:
import Firebase from 'firebase'
/**
* Pega aquí los datos de tu proyecto firebase
*/
const firebaseApp = Firebase.initializeApp({
apiKey: "++++******-sU0qfey9278aBIDP6zo",
authDomain: "*+****+.firebaseapp.com",
databaseURL: "https://*****.firebaseio.com",
projectId: "+++++",
storageBucket: "**.appspot.com",
messagingSenderId: "**"
});
export const db = firebaseApp.database()
export const storage = firebaseApp.storage()
export const auth = firebaseApp.auth()
// export const notif = firebase.messaging()
in the terminal this is what I get:
$route
downloadURL:"" --->here shoud get the URL
file:ƒ File()
progressUpload:100
uploadTask:Object
authWrapper_:Object
blob_:Object
chunkMultiplier_:1
errorHandler_:ƒ (error)
error_:null
location_:Object
mappings_:Array[15]
metadataErrorHandler_:ƒ (error)
metadata_:Object
Thank so much in advance
i had the same problem, i tried a lot of stuff, but the simply one solution i found was:
to change the Firebase versión in my package.json i switched to: "firebase": "^4.6.2".
I am not sure what's happening with the 5.0.2 version. Even when that solve the problem i am still looking for the docs of the change maybe we need to use the snapshot in a different way. will see.
Good luck! ;)
-- BlisS
Update:
The issue is that the snapshop no longer own the downloadURL at version 5, now you have tu use the method getDownloadURL that belongs to the ref, just like pushups said, something like this:
const fileRef = firebase.storage()
.ref("carpeta")
.child(file.name);
const uploadTask = fileRef.put(file);
uploadTask
.then(snap=>{
return fileRef.getDownloadURL()
})
this also works:
return snap.ref.getDownloadURL()
You can get this to work with Firebase 5.2.0 with the following code.
The UploadTaskPromise yields a snapshot. The snapshot has a ref property. The ref property has a getDownloadURL() function which returns a Promise. That Promise gives the downloadable url once it's available.
https://firebase.google.com/docs/reference/js/firebase.storage.Reference#getDownloadURL
uploadTask.then((snapshot) => {
snapshot.ref.getDownloadURL().then((url) => {
// do something with url here
});
});
Use this code:
import {launchImageLibrary} from 'react-native-image-picker';
import storage from '#react-native-firebase/storage';
launchImageLibrary({quality: 0.5}, response => {
let data = response.assets[0];
const uploadTask = storage()
.ref()
.child(`/uploadedphotos/${Cid}`)
.putFile(data.uri);
uploadTask.on(
'state_changed',
snapshot => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
if (progress == 100) Alert.alert('File Upload Complete');
},
error => {
Alert.alert(error);
},
() => {
uploadTask.snapshot.ref
.getDownloadURL()
.then(downloadURL => {
console.log('File available at', downloadURL);
})
},
);