简体   繁体   中英

How do I initialize data for Flux using Gulp and Browserify?

I am using Gulp and Browserify to generate a bundle.js file.

gulp.task('js', function () {
    browserify('./js/app.js')
        .transform(reactify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./js/'));
   });

I am now trying to initialize my Flux application with data from the server so that there is no wait time when the page loads.

According to Bill Fisher this should be done in a bootstrap file like this one (slide 62): https://speakerdeck.com/fisherwebdev/flux-meetup#62

My question is where is the bootstrap function being called?

I have seen people using the command line to generate a bundle that allows you to use require in the global scope. I have also seen people put their JSON data into script tags and assign it to the window variable.

This all seems very messy to me. What's the best practice for this?

I would prefer:

<script type='text/javascript'>
    MyApp.initialize({{json}});
</script>

Also, the data I'm loading is from a database. As most of the Flux examples so far only use localStorage it doesn't help me when trying to asynchronously load data.

Found the answer somewhere online; add {standalone: 'app_name'} to your config.

gulp.task('js', function () {
    browserify('./js/app.js', {standalone: 'MyApp'})
        .transform(reactify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./js/'));
});

Then you can do new MyApp() from within script tags on your page.


Update 09/09/15 New Approach

I have since changed my approach to using babelify instead of reactify and no longer having to call my javascript from inside script tags.

var b = watchify(browserify('js/index.js', {
    cache: {},
    packageCache: {},
    debug: true,
    fullPaths: true,
    transform: ['babelify']
}));

function bundler () {
    b.bundle()
        .on('error', gutil.log.bind(gutil, 'Browserify error.'))
        .pipe(source('build.js'))
        .pipe(gulp.dest('/js'));
}

gulp.task('backend:scripts', bundler);
b.on('update', bundler);
b.on('log', gutil.log);

Also, should note that regarding the original question and bootstrapping data I now use express-state .

res.expose({
    users: users,
    posts: posts
});

And then in your handlebars file:

<script type="text/javascript">{{{state}}}</script>
<script src="/js/build.js" type="text/javascript"></script>

And all your data is available on the window variable for bootstrapping within your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM