React ES6 SystemJS - Uncaught (in promise) Error: Unexpected token <(…)

React ES6 SystemJS - Uncaught (in promise) Error: Unexpected token <(…)

我通过下面的 System.config 安装并导入了 reactreact-dom,但我仍然收到以下错误:

Uncaught (in promise) Error: Unexpected token <(…)

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ES2015 Module Example</title>
</head>
<body>
    <script src="lib/system.js"></script>
    <script>
        System.config({
            "baseURL": "src",

            // Set defaultJSExtensions to true so you don't have to use .js extension when importing the es6 module.
            "defaultJSExtensions": true,

            // 'plugin-babel' or 'traceur' or 'typescript'
            transpiler: 'traceur',

            map: {
                'react': './node_modules/react/dist/react.min.js',
                'react-dom': './node_modules/react-dom/dist/react-dom.min.js',
                'traceur': './lib/traceur.min.js',
                'plugin-babel': './lib/plugin-babel/plugin-babel.js',
                'systemjs-babel-build': './lib/plugin-babel/systemjs-babel-browser.js'
            },
        });
        System.import("app.js");
    </script>
</body>
<div id="example"></div>
</html>

app.js:

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

var Hello = React.createClass({
    render: function() {
        return <h1>Hello {this.props.name}</h1>;
    }
});

ReactDOM.render(
    <Hello name="World" />,
    document.getElementById('example')
);

知道我还需要配置什么吗?

Unexpected token < 通常出现在 html5 应用程序中,当服务器配置为 return index.html 的内容而不是 404 页面时(因此在动态路由上按 f5仍然有效)。然后检查浏览器开发人员控制台中的网络面板,并查看哪个 js 文件提供了 html 内容。

browserify 是最好的解决方案(用于生产和开发)- 对我来说:

npm install --save-dev babel-preset-react

gulp:

var gulp = require('gulp');

var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var livereload = require('gulp-livereload');

gulp.task('build', function() {
    // app.js is your main JS file with all your module inclusions
    return browserify({entries: 'src/app.js', debug: true})
        .transform("babelify", { presets: ["es2015", "react"] })
        .bundle()
        .pipe(source('compile.min.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init())
        .pipe(uglify())
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest('js'))
        .pipe(livereload());
});

gulp.task('default', ['build']);

至于使用 SystemJS 的非生产环境(非常慢):

<!DOCTYPE html>
<script src="https://jspm.io/system@0.19.js"></script>
<script>
System.config({
  transpiler: 'babel',
  babelOptions: {}
});
System.import('./main.js');
</script>

您仍然可以使用 gulp 进行开发。只需将其添加到 gulp 文件中:

gulp.task('watch', ['build'], function () {
    livereload.listen();
    gulp.watch('js/*.js', ['build']);
});

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

这使您免于其他繁琐的开发工作流程,如 listed 此处。