我使用guide创建了项目。项目工作,我看到了Hello World。
所以我使用 frontend-maven-plugin 并命令mvn clean install
打包我的前端。
但现在我想将ReactJS添加到这个项目中。
我的app.jsx:
import React from "react";
import ReactDom from "react-dom";
class App extends React.Component {
render() {
return "<p>Hello from React to the World!</p>"
}
}
const app = document.getElementById("react");
const element=<App />;
const ref = ReactDOM.render(element, app);
的package.json:
{
"name": "fe",
"version": "1.0.0",
"description": "Description",
"main": "./app",
"scripts": {
"build": "webpack -p"
},
"author": "",
"license": "ISC",
"devDependencies": {
"react-frame-component": "^2.0.2",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"requirejs": "^2.3.5"
}
}
webpack.config.js:
var packageJSON = require('./package.json');
var path = require('path');
var webpack = require('webpack');
const PATHS = {
build: path.join(__dirname, 'target', 'classes', 'META-INF', 'resources', 'webjars', packageJSON.name, packageJSON.version)
};
module.exports = {
entry: './app/index2.js',
output: {
path: PATHS.build,
filename: 'app-bundle.js'
},
resolve: {extensions: ['.js', '.jsx']}
};
index2.js:
import App from './app.jsx';
当我申请mvn clean install
时,我遇到以下错误:
[INFO] app-bundle.js 827 bytes 0 [emitted] main
[INFO] [0] ./app/index2.js 28 bytes {0} [built]
[INFO] [1] ./app/app.jsx 254 bytes {0} [built] [failed] [1 error]
[INFO]
[INFO] ERROR in ./app/app.jsx
[INFO] Module parse failed: Unexpected token (12:14)
[INFO] You may need an appropriate loader to handle this file type.
[INFO] | const app = document.getElementById("react");
[INFO] |
[INFO] | const element=<App />;
[INFO] | const ref = ReactDOM.render(element, app);
[INFO] @ ./app/index2.js 1:0-28
[ERROR] npm ERR! code ELIFECYCLE
[ERROR] npm ERR! errno 2
[ERROR] npm ERR! fe@1.0.0 build: `webpack -p`
[ERROR] npm ERR! Exit status 2
这意味着意外的令牌是<App />;
之前的一封信。
如果我使用引号 const element =&#34; &LT; App /&gt; ; &#34; 它说:Unexpected token: name (App) [app-bundle.js:263,6]
你能提醒我,我错过了什么吗?使用 frontend-maven-plugin 打包ReactJS项目需要做什么?
答案 0 :(得分:0)
您需要为React的代码正确设置加载程序。 最简单的方法是使用Babel:
npm install -D babel-loader babel-core babel-preset-env babel-preset-react
将rules
部分放入您的webpack配置
module : {
rules: [{
test : /\.jsx?/,
exclude: /node_modules/,
loader : 'babel-loader',
options: {
presets: ["env", "react"]
}
}]
}
本教程似乎足够新鲜:https://www.valentinog.com/blog/react-webpack-babel/