Splitting React components into separate files

2019-05-17 12:33发布

This seems to be a common question, I'm finding a lot of people asking it and the responses are all very different and seem to be a bit hit and miss. I've watched various video tutorials, read plenty of tutorials, and the documentation. But alas it seems React is moving faster than the writers can keep up with. Or I'm just misunderstanding.

I want to create each component in a separate file, where logical to do so. I have React working, but am unable to work out how to import and use additional files. I don't know if this is because Chrome will not load in files when not on a web server (local test dev), or if I'm just going about it all wrong.

Here is my HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Test One</title>
</head>
<body>
<div id="rootNode"></div>
<script src="dist/bundle.js"></script>
</body>
</html>

And here is my main.js:

var React = require('react');
var ReactDOM = require('react-dom');
var Square = require('../components/square.jsx').square;

ReactDOM.render(
    <div>
        <h1>Hello React!</h1>
        <Square />
    </div>,
    document.getElementById('rootNode')

);

This works fine if I don't try to use Square also.

This is my square.jsx:

class Square extends React.Component{
    render() {
        return (
            <p>Square</p>
        )
    }
}

module.exports = {
    square: Square
};

Babel create the bundle.js fine, no errors. Chrome throws the error:

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

I have tried the following also for square, along with many other things, all lost from the undo queue:

import React from 'react';

class Square extends React.Component{
    render() {
        return (
            <p>Square</p>
        )
    }
}

export default Square;

All help appreciated. React seems to make sense aside from separating out the class files.

Thanks.

EDIT:

Also tried:

var {Component} = React;

class Square extends Component{
    render() {
        return (
            <p>Square</p>
        )
    }
}

window.Square = Square;

And if it helps here is the Gulp file:

var vendors = [
    'react'
];

gulp.task('vendors', function () {
    var stream = browserify({
        debug: false,
        require: vendors
    });

    stream.bundle()
        .pipe(source('./src/main.js'))
        .pipe(gulp.dest('./dist/bundle.js'));

    return stream;
});

And the package.json:

{
  "name": "reacttestone",
  "version": "1.0.0",
  "description": "Testing React Components",
  "main": "index.js",
  "dependencies": {
    "babel-preset-react": "^6.1.2",
    "babelify": "^7.2.0",
    "react": "^0.14.2",
    "react-dom": "^0.14.2"
  },
  "devDependencies": {
    "gulp": "^3.9.0",
    "vinyl-source-stream": "^1.1.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Myself",
  "license": "MIT"
}

1条回答
Luminary・发光体
2楼-- · 2019-05-17 12:51

Your es6 example of exporting like export default Square should work fine. It looks like you've installed babelify but you're not using it in the transform process, hence why the browser is complaining that you're trying to use es6 features outside of strict mode.

If you look at the babelify instructions it says to do something like:

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var gutil = require('gulp-util');

gulp.task('browserify', function () {
    browserify('./src/main.js', { debug: true })
        .transform('babelify', {presets: ['es2015', 'react']})
        .bundle()
        .on('error', gutil.log)
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./dist'))
});

gulp.task('watch',function() {
    gulp.watch('./src/**/*.js', ['browserify'])
});

It looks like you only have babel-preset-react installed, you'll need to do npm i babel-preset-es2015 --save-dev. Also babelify and babel-preset-react are fine as devDependencies.

查看更多
登录 后发表回答