使用JXS导入react组件时出现问题。组件是从库中导入的(用作SDK)。
/sdk/dist/js/app.js
import React, { Component } from 'react';
export default class Test extends Component {
render() {
return <div>Hello</div>;
}
}
有一个使用此SDK的项目,有webpack / babel已经在构建,导入该组件的文件如下所示:
app / js / index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Test from 'sdk/dist/js/App';
但是! 一切都会在以下情况下起作用:
app / js / index.js
import React, { Component } from 'react';
export default class Test extends Component {
render() {
return React.createElement(
"div",
null,
"Hello"
);
}
}
app / js / index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Test extends Component {
render() {
return <div>Hello</div>;
}
}
问题在于它需要通过导入来工作。我建议问题是webpack不会转置导入的文件-而是按原样读取它...
webpack:
{
entry: './app/js/index.js',
output: {
path: resolve(__dirname, plConfig.paths.public.root),
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: "babel-loader",
options: {
cacheDirectory: true
}
}
]
}
]
}
.babelrc:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
答案 0 :(得分:0)
您需要babel插件来转换jsx ...
@babel/plugin-transform-react-jsx
安装
npm i -D @babel/plugin-transform-react-jsx
在.babelrc中使用
{
presets: [ ... ],
plugins: [ "@babel/plugin-transform-react-jsx", ...other plugins ]
}
编辑:
您还需要为 jsx 添加babel规则... 在您的webpack模块规则中...
将test: /\.js$/
更改为test: /\.jsx?$/