gpt4 book ai didi

javascript - babel-loader 语法错误仅适用于导入的模块

转载 作者:行者123 更新时间:2023-12-01 04:01:46 24 4
gpt4 key购买 nike

最初,我有以下可编译和运行的 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) 中时,我收到“模块构建失败:语法错误:lib.js 的意外标记 (5:1)。我看不到为什么当我将组件移入 lib.js 后 babel 不负责转译。请帮忙(我是 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 表达式。

关于javascript - babel-loader 语法错误仅适用于导入的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42146878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com