[英]babel-loader syntax error only for imported modules
最初,我有下面的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)中分离组件时,出现“模块构建失败:SyntaxError:lib.js的意外令牌(5:1)。 我看不到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"
}
]
}
}
export const hello = {
<h1 id="title"
className="header"
style={{backgroundColor: 'turquoise', color: 'white', fontFamily: 'verdana'}}>
{text.hello}
</h1>
}
{...}
被解释为对象文字。 您不能将JSX放在对象文字中,就像您不能在对象文字中放入任意代码一样。
例如,这引发了类似的错误:
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表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.