gulp converting React module to class error - javascript

after converting a simple react module to es6 class; i got some gulp parsing errors.
var React = require('react');
// import React from 'react';
class UdpComp extends React.Component {
constructor (props){
super(props);
this.state = { udpinput: props.udpinput };
},
render: function() {
return(
<div className="udpText">
<h2>UDP-INPUT: {this.state.udpinput}</h2>
</div>
) // return
} // render
})// UdpComp
export default UdpComp;
ok, my gulpfile.babel.js looks like this:
var gulp = require('gulp'),
browserify = require('gulp-browserify'),
concatCss = require('gulp-concat-css'),
sass = require('gulp-sass'),
run = require('gulp-run');
var src = './process',
app = './app';
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded'
}; // https://www.sitepoint.com/simple-gulpy-workflow-sass/
gulp.task('js', function() {
return gulp.src( src + '/js/apprender.js' )
.pipe(browserify({
transform: 'reactify',
extensions: 'browserify-css',
debug: true
}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(gulp.dest(app + '/js'));
});
gulp.task('html', function() {
gulp.src( src + '/**/*.html');
});
gulp.task('css', function() {
gulp.src( src + '/css/*.css')
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(concatCss('app.css'))
.pipe(gulp.dest(app + '/css'));
});
gulp.task('fonts', function() {
gulp.src('node_modules/bootstrap/dist/fonts/**/*')
.pipe(gulp.dest(app + '/fonts'));
});
gulp.task('watch', ['serve'], function() {
gulp.watch( src + '/js/**/*', ['js']);
gulp.watch( src + '/css/**/*.css', ['css']);
gulp.watch([ app + '/**/*.html'], ['html']);
});
gulp.task('serve', ['html', 'js', 'css'], function() {
run('electron app/main.js').exec();
});
gulp.task('default', ['watch', 'fonts', 'serve']);
when calling gulp I get
\process\js\UdpCompReact.js: Parse Error: Line 14: Unexpected
identifier error
why, how can I parse es6 code?

Can't see what's on line 14 but I'd guess it's the comma right after your constructor. As opposed to ES5 "classes", ES6 classes don't require (and don't allow) commas between methods. Just remove it and it should work (or at least get past line 14)

You need a transpiler that converts it to ES5, afterwards pipe it in the gulp task. I use babel and there is a gulp-babel npm package

I changed my code to this, when using the older version the transpiling works.
import React from 'react' throws an error.
// var React = require('react');
import React from 'react';
class UdpComp extends React.Component {
constructor (props){
super(props);
this.state = { udpinput: this.props.udpinput };
}
render () {
return(
<div className="udpText">
<h2>UDP-INPUT: {this.state.udpinput}</h2>
</div>
) // return
} // render
}; // UdpComp
module.exports = UdpComp;
// export default UdpComp;

Related

Create class instance and inject it dynamically

My project is using Nuxt, and I would like to implement dynamic injection of my services. It means I just add a class to my specific folder, and the class will be automatically injected into the context.
For instance, these are my classes placed in nuxtApp/service:
// /service/foo.service.js
export class FooService {
constructor (context) {
this.context = context
}
functionFoo (param) {
console.log(`FooService.functionFoo: ${param}`)
}
}
// /service/bar.service.js
export class BarService {
constructor (context) {
this.context = context
}
functionBar (param) {
console.log(`BarService.functionBar: ${param}`)
}
}
And this is how my plugin currently looks like, but I would like to automate it:
// /plugins/service-loader.js
import { FooService } from '../service/foo.service'
import { BarService } from '../service/bar.service'
export default ({ app }, inject) => {
const fooService = new FooService(app)
inject('fooService', fooService)
const barService = new BarService(app)
inject('barService', barService)
}
Is it possible to create automatically loading of services placed in the /service folder, and then inject their instance into the context?
You could use a Nuxt module to provide plugins for ~/service/*.service.js. The module would scan the service/ directory, and call addPlugin() for each .service.js file:
// ~/modules/service-loader.js
import path from 'path'
import glob from 'glob'
export default function serviceLoader() {
glob(path.resolve(__dirname, '../service/**/*.service.js'), { follow: true }, (err, files) => {
if (err) throw err
for (const file of files) {
const exportedMembers = Object.keys(require(file))
if (!exportedMembers.length) return
const className = exportedMembers[0]
this.addPlugin({
src: path.resolve(__dirname, './service-template.js'),
fileName: path.basename(file),
options: {
className,
propName: className.slice(0,1).toLowerCase() + className.substring(1),
moduleName: file,
}
})
}
})
}
// ~/modules/service-template.js
import { <%= options.className %> } from '<%= options.moduleName %>'
export default ({ app }, inject) => {
const <%= options.propName %> = new <%= options.className %> (app)
inject('<%= options.propName %>', <%= options.propName %>)
}
Install this module under the modules array in your Nuxt config:
// nuxt.config.js
export default {
modules: [
'~/modules/service-loader'
],
}

Rollup with CommonJS, import and exports with treeshaking

I'm trying to get rollup, commonjs, es6 and tree shaking working correctly.
Currently, I have the following build script:
'use strict';
const rollup = require('rollup');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
rollup.rollup({
input: 'main.js',
format: 'iife',
plugins: [
{
transform(code, id) {
return code;
}
},
resolve({
extensions: ['.js', '.jsx']
}),
commonjs({
extensions: ['.js', '.jsx']
})
]
})
.then(({ generate }) => generate({
format: 'iife',
name: 'test',
}))
.then(({ code }) => console.log(code));
which loads the following main.js file
const { firstFunction } = require('./exports');
firstFunction();
and the export.js file
export function firstFunction() {
return this.name;
}
export function secondFunction() {
return this.name;
}
outputs the following:
var test = (function () {
'use strict';
function firstFunction$1() {
return this.name;
}
function secondFunction() {
return this.name;
}
var exports$1 = Object.freeze({
firstFunction: firstFunction$1,
secondFunction: secondFunction
});
var require$$0 = ( exports$1 && undefined ) || exports$1;
const { firstFunction } = require$$0;
firstFunction();
var main = {
};
return main;
}());
I am unsure if this is the correct behaviour, I was assuming that I would be able to use tree-shaking with the es6 export.js file and therefore not need to import the secondFunction() from export.js in our bundled code.
I have tried a number of combinations of settings but nothing seems to be able to get tree-shaking to work.
It's worth noting that I'm using commonjs on the server and trying to use the same file bundled on the client - this is why I have a mix of cjs and es6.
As stated by Lux in comments, the problem is you're mixing cjs and ES modules. It seems the rollup-plugin-commonjs does not treeshake the imports.
You should first bundle your files with rollup and use cjs as output format. You then require the bundle.
That should get your javascript treeshaken and ready for node.

Typescript module not loading after compile

New to Angular/ts/js. I went through the Tour of Heroes tutorial, now I am trying to incorporate compiling and building via gulp. Seems to be going well enough but I can't seem to figure this roadblock out.
In a single example, I have the app/components/app.module.ts file (disregard the deep relative import pathing; I plan on refactoring it later):
import { BrowserModule } from '../../node_modules/#angular/platform-browser';
import { NgModule } from '../../node_modules/#angular/core';
import { FormsModule } from '../../node_modules/#angular/forms';
import { HttpModule } from '../../node_modules/#angular/http';
import { InMemoryWebApiModule } from '../../node_modules/angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HeroService } from './hero.service';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroSearchComponent } from './hero-search.component';
#NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService, { delay: 600 })
],
declarations: [
AppComponent,
DashboardComponent,
HeroSearchComponent,
HeroesComponent,
HeroDetailComponent,
],
providers: [HeroService],
bootstrap: [AppComponent]
})
export class AppModule { }
After I compile it to js and serve up the application, the console tells me:
"Cannot GET /js/components/app.component"
(along with all the other modules after it), even though that js DOES exist at the location.
I believe I found that it's still expecting it to be the ts file. If I explicitly change the import to be a js file as
"import { AppComponent } from './app.component.js';"
then it loads fine.
In my research, I think I may need a sourcemap, but being entirely green at this I'm not sure. I'm not entirely sure how to describe/define the issue so web searches haven't netted me anything definitive. Can someone get me on the right track?
Update
Here is my gulpfile. Still learning so I know it's messy.
// grab our packages
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
clean = require('gulp-clean'),
connect = require('gulp-connect'),
gnf = require('gulp-npm-files');
const tscConfig = require('./tsconfig.json');
var ts = require('gulp-typescript');
var merge = require('merge2');
// define the default task and add the watch task to it
gulp.task('default', ['watch']);
// configure the jshint task
gulp.task('jshint', function() {
return gulp.src('app/components/js/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {
gulp.watch('app/components/js/**/*.js', ['jshint']);
});
gulp.task('compileTs', function () {
var tsResult = gulp.src('app/**/*.ts')
.pipe(ts({
declaration: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('dist/definitions')),
tsResult.js.pipe(gulp.dest('dist/js'))
]);
});
gulp.task('compileEnviroTs', function () {
var tsResult = gulp.src('environments/**/*.ts')
.pipe(ts({
declaration: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('dist/definitions')),
tsResult.js.pipe(gulp.dest('dist/environments'))
]);
});
gulp.task('cleanDist', function() {
return gulp.src('dist', {read: false})
.pipe(clean());
});
gulp.task('copyDeps', ['cleanDist'], function() {
gulp
.src(gnf(null, './package.json'), {base:'./'})
.pipe(gulp.dest('dist'));
});
gulp.task('copyEnvironments', ['copyDeps'], function() {
return gulp.src('environments/**/*')
.pipe(gulp.dest('dist/environments'));
});
gulp.task('copyComponents', ['copyEnvironments'], function() {
return gulp.src('app/components/**/*')
.pipe(gulp.dest('dist/components'));
});
gulp.task('copyCss', ['copyComponents'], function() {
return gulp.src('app/css/**/*')
.pipe(gulp.dest('dist/css'));
});
gulp.task('copyImg', ['copyCss'], function() {
return gulp.src('app/img/**/*')
.pipe(gulp.dest('dist/img'));
});
gulp.task('copyJs', ['copyImg'], function() {
return gulp.src('app/js/**/*')
.pipe(gulp.dest('dist/js'));
});
gulp.task('copyPartials', ['copyJs'], function() {
return gulp.src('app/partials/**/*')
.pipe(gulp.dest('dist/partials'));
});
gulp.task('copyFiles', ['copyPartials'], function() {
return gulp.src('app/**/*')
.pipe(gulp.dest('dist'));
});
gulp.task('connect', ['copyFiles', 'compileTs'], function () {
connect.server({
root: 'dist/',
port: 8888
});
});
gulp.task('dev', ['cleanDist', 'compileTs', 'compileEnviroTs', 'copyDeps', 'copyFiles', 'connect']);
Update
Here is my code repo, if it helps any. I'm in the gulp branch.
https://github.com/fmjnax/LearningAngular.git

Typescript complaining about namespace

I am using node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. When I build with gulp I get an error.
Here is my code
/// <reference path="../_all.d.ts" />
'use strict';
import * as Pool from '~mysql/lib/Pool';
import * as mysql from 'mysql';
import * as conf from '../config/config';
class DbConnection {
public pool: Pool;
public static bootstrap(): DbConnection {
return new DbConnection();
}
constructor() {
const setting: conf.Setting = (new conf.Config()).config();
this.pool = mysql.createPool({
connectionLimit: 10,
host: setting.infiniDbHost,
user: setting.infiniDbUser,
password: setting.infiniDbPassword,
debug: false
});
}
}
const dbConnection: DbConnection = DbConnection.bootstrap();
export default dbConnection.pool;
Here is the error that I get:
[11:21:07] Using gulpfile ~/Repos/git/WdAnalytics/gulpfile.js
[11:21:07] Starting 'clean'...
[11:21:07] Finished 'clean' after 21 ms
[11:21:07] Starting 'default'...
src/data/infiniDbConnection.ts(28,16): error TS2503: Cannot find namespace 'dbConnection'.
[11:21:08] TypeScript: 1 semantic error
[11:21:08] TypeScript: 2 emit errors
[11:21:08] TypeScript: emit failed
[11:21:08] Finished 'default' after 1.38 s
Here is my gulpfile.js
var gulp = require('gulp');
var ts = require('gulp-typescript');
var clean = require('gulp-clean');
var src = ['src/**/*.ts', '!src/_all.d.ts'];
gulp.task('default', ['clean'], function() {
return gulp.src(src)
.pipe(ts({
noImplicitAny: true,
noEmitOnError: true
}))
.pipe(gulp.dest('dist/.'))
;
});
gulp.task('clean', function() {
return gulp.src('dist/.', {read: false})
.pipe(clean())
;
});
I can't figure out why it thinks dbConnection is a namespace when it is clearly an object.
I changed noEmitOnError: true to noEmitOnError: false and it still tells me there is a semantic error but it builds and runs just fine.

Require file with a variable in React JS

I'm trying to require a file with a variable in the path. Something like
const langCode = this.props.langCode; // en
let languageFile = require('../common/languages/' + langCode);
Where langCode can be fr, en, de, nl. Thus what I'm trying to get is for example
require('../common/languages/en');
When I type it without variable at the end, thus require('../common/languages/en'); it works good. But when I try with require('../common/languages/' + langCode); it won't work, doesn't matter that the value of the langCode is also en.
I get next error :
bundle.js:1 Uncaught Error: Cannot find module '../common/languages/en'
UPDATE
'use strict';
var gulp = require('gulp');
var connect = require('gulp-connect');
var open = require('gulp-open');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var concat = require('gulp-concat');
var babelify = require('babelify');
var sass = require('gulp-sass');
var merge = require('merge-stream'); // Merge all styles (css, sass and less) in one big bundle
var lint = require("gulp-eslint");
var config = {
port: 8001,
devBaseUrl: 'http://localhost',
paths: {
html: "./src/*.html",
externals: "./src/assets/externals/*.js",
js: "./src/**/*.js",
images: './src/assets/images/**/*',
fonts: './src/assets/css/fonts/*',
css: [
"./src/assets/css/*.css",
"./node_modules/toastr/package/toastr.css"
],
sass: './src/assets/css/*.scss',
dist: "./dist",
mainJS: "./src/main.js"
}
};
gulp.task('connect', ['watch'], function () {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true,
fallback: './dist/index.html'
})
});
gulp.task('open', ['connect'], function () {
gulp.src('dist/index.html')
.pipe(open({uri: config.devBaseUrl + ":" + config.port + "/"}));
});
gulp.task('html', function () {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('externals', function () {
gulp.src(config.paths.externals)
.on('error', console.error.bind(console))
.pipe(concat('external.js'))
.pipe(gulp.dest(config.paths.dist + '/externals'))
.pipe(connect.reload());
});
gulp.task('js', function () {
browserify(config.paths.mainJS)
.transform('babelify', {presets: ['es2015', 'react']})
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('images', function () {
gulp.src(config.paths.images)
.pipe(gulp.dest(config.paths.dist + '/images'));
});
gulp.task('styles', function () {
var cssStyles = gulp.src(config.paths.css)
.pipe(concat('styles.css'));
var sassStyles = gulp.src(config.paths.sass)
.pipe(sass())
.pipe(concat('styles.scss'));
var mergedStream = merge(cssStyles, sassStyles)
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'))
.pipe(connect.reload());
return mergedStream;
});
gulp.task('fonts', function () {
gulp.src(config.paths.fonts)
.pipe(gulp.dest(config.paths.dist + '/css/fonts'));
});
gulp.task('lint', function () {
return gulp.src(config.paths.js)
.pipe(lint())
.pipe(lint.format());
});
gulp.task('watch', function () {
gulp.watch(config.paths.html, ['html']);
gulp.watch(config.paths.js, ['js', 'lint']);
gulp.watch(config.paths.externals, ['externals', 'lint']);
gulp.watch([config.paths.css, config.paths.sass], ['styles']);
gulp.watch(config.paths.images, ['images']);
});
gulp.task('default', ['html', 'js', 'styles', 'externals', 'images', 'fonts', 'lint', 'open', 'watch']);
Most of JS bundlers cannot handle dynamic require mechanism.
Try to load all languages and switch them in runtime
let languages = {
en: require('../common/languages/en'),
ru: require('../common/languages/ru'),
de: require('../common/languages/de')
}
const langCode = this.props.langCode; // en
let languageFile = languages[langCode];
Are you using webpack as your bundler?
If so you need to be aware of it's dynamic requires mechanism.
Here is an issue that discusses it.
in your express.js server, set up a static directory containing any static.file:
const express = require('express')
const app = express()
app.use(express.static(path.join(__dirname, '../path_to/..', staticImages)))
react native component:
return <Image source={{ uri: `http://192.168.0.1:3345/${'staticImage.jpg'}`}} />

Categories