2

I have app structure:

-- dist
   - index.html
-- js
   - index.js
- package.json
- package-lock.json
- gulpfile.js

In index.html I have this:

<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <link rel="stylesheet" type="text/css" href="/css/main.css">
    </head>
    <body>
        <div id='root'></div>
        <script type="text/javascript" src="/js/index.js"></script>
    </body>
</html>

In index.js I have this simple React app:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render((
  <h1>Hello world</h1>),
  document.getElementById('root')
);

And this script in Gulp with appropriate imports and packages:

gulp.task('js', () =>
    gulp.src('js/*.js')
    .pipe(babel({
        presets: ['env', 'react', 'es2015']
    }))
    .pipe(gulp.dest('dist/js'))
);

gulp.task('webserver', function() {
    gulp.src('dist')
        .pipe(webserver({
            livereload: true,
            directoryListing: true,
            open: 'http://localhost:8000/index.html'
        }));
});

gulp.task('watch', function() {
    gulp.watch('styles/**/*.less', ['less']);
    gulp.watch('js/**/*.js', ['js']);
    gulp.src('dist')
        .pipe(webserver({
            open: 'http://localhost:8000/index.html'
        }));
});

// + less

gulp.task('default', [ 'less', 'watch', 'js']);

It correctly creates copy of js files and add them to the dist/js folder and the server start running. The first load throw error in console Failed to load resource: the server responded with a status of 404 (Not Found) index.js:1 but on second load it works fine but throw error Uncaught ReferenceError: require is not defined index:3.

I found on the internet similar cases and the advice was to use browserify or webpack. I tried this script to bundle everything instead of the above code:

gulp.task('js', function () {
    var b = browserify({
      entry: './js/*.js',
      debug: true,
      transform: [babelify.configure({
        presets: ['env', 'react', 'es2015']
      })]
    });

    return b.bundle()
      .pipe(source('index.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
          // Add transformation tasks to the pipeline here.
          .pipe(uglify())
          .on('error', log.error)
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./dist/js/'));
  });

The application loads but the React is not there. it creates accordingly index.js and index.map but the DOM is not updated from the React.

It's the first time using Gulp so I am not sure what I am doing wrong.

Petr
  • 1,853
  • 2
  • 25
  • 49
  • 2
    I would say there is definitely a solution to your problem if you continue to use Gulp, I don't see what the issue could be, briefly reviewing your code. You should just use webpack though, it has "won" if you will – Brian Ogden Nov 15 '19 at 17:59

0 Answers0