2017-02-09 139 views
0

巴贝尔装载机语法错误最初我有下面index.js文件编译和运行:仅导入模块

import React from 'react'; 
import { render } from 'react-dom'; 
import text from './titles.json'; 

render(
    <div> 
     <h1 id="title" 
      className="header" 
      style={{backgroundColor: 'turquoise', color: 'white', fontFamily: 'verdana'}}> 
      {text.hello} 
     </h1> 
     <h1 id="title" 
      className="header" 
      style={{backgroundColor: 'brown', color: 'white', fontFamily: 'verdana'}}> 
      {text.goodbye} 
     </h1> 
    </div>, 
    document.getElementById('react-container') 
) 

然而,当我在一个单独的文件(LIB分离出的组件。 js),我得到了“Module build failed:SyntaxError:意外的令牌(5:1)for lib.js. 我不明白为什么babel没有照顾一旦我将组件转移到lib.js。请帮忙(我是React,Webpack,Babel的新手)

lib.js

import React from 'react'; 
import text from './titles.json' 

export const hello = { 
    <h1 id="title" 
     className="header" 
     style={{backgroundColor: 'turquoise', color: 'white', fontFamily: 'verdana'}}> 
     {text.hello} 
    </h1> 
} 

export const goodbye = { 
    <h1 id="title" 
     className="header" 
     style={{backgroundColor: 'brown', color: 'white', fontFamily: 'verdana'}}> 
     {text.goodbye} 
    </h1> 
} 

修改index.js

import React from 'react'; 
import { render } from 'react-dom'; 
import { hello, goodbye } from './lib.js'; 

render(
    <div> 
     {hello} 
     {goodbye} 
    </div>, 
    document.getElementById('react-container') 
) 

这里是我的WebPack配置文件:

var webpack = require("webpack"); 

module.exports = { 
    entry: "./src/index.js", 
    output: { 
     path: require("path").resolve("dist/assets"), 
     filename: "bundle.js", 
     publicPath: "assets" 
    }, 
    devServer: { 
     inline: true, 
     contentBase: "./dist", 
     port: 3000 
    }, 
    module: { 
     loaders: [ 
      { 
       test: /\.js$/, 
       exclude: /(node_modules)/, 
       loader: "babel-loader", 
       query: { 
        presets: ["latest", "react", "stage-0"] 
       } 
      }, 
      { 
       test: /\.json$/, 
       exclude: /(node_modules)/, 
       loader: "json-loader" 
      } 
     ] 
    } 
} 

回答

2
export const hello = { 
    <h1 id="title" 
     className="header" 
     style={{backgroundColor: 'turquoise', color: 'white', fontFamily: 'verdana'}}> 
     {text.hello} 
    </h1> 
} 

{...}被解释为对象文本。您不能将JSX放入对象文字中,就像您不能将任意代码放入对象文字中一样。

E.g.这会抛出类似的错误:

export const hello = { 
1 + 1 
} 

如果您要导出React元素,那么就这样做。删除{...}

export const hello = 
    <h1 id="title" 
     className="header" 
     style={{backgroundColor: 'turquoise', color: 'white', fontFamily: 'verdana'}}> 
     {text.hello} 
    </h1>; 

里面 JSX,{...}具有不同的意义。例如。在

<span>{1+1}</span> 

{...}让解析器知道内容是一个JavaScript表达式。

+0

OMG,谢谢,傻我! – hcabrams