尝试使用React项目目录之外的目录中的组件并通过webpack进行构建,但出现以下错误。
SyntaxError: /Users/cmc/Sites/common/form_builder/src/index.js: Unexpected token (8:12)
6 |
7 | render(
> 8 | <div>
| ^
9 | common
10 | </div>
11 | )
文件夹结构
我尝试安装具有与react项目相同的依赖项的node_modules,还添加了相同的.babelrc文件。
webpack.config.json
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'index_bundle.js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
include: [
"/Users/cmc/Sites/common/form_builder/",
path.resolve(__dirname, ""),
]}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
}```
.babelrc
```{
"presets": [
"@babel/env",
"@babel/react"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
package.json
{
"name": "webpack-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --hot",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.18.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/plugin-proposal-class-properties": "^7.4.4",
"@babel/preset-env": "^7.4.4",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1",
"webpack-dev-server": "^3.3.1"
}
}
App.js
import React, { Component } from 'react';
import Test from '../../../common/form_builder/src/index';
class App extends Component {
render() {
return(
<div>
<Test />
</div>
);
}
}
export default App;
index.js
import React, { Component } from '../../webpack-test/node_modules/react';
class Test extends Component {
render() {
return(
<div>
Test
</div>
)
}
}
export default Test;
完全错误:
[./ node_modules / webpack / hot / log-apply-result.js](webpack)/ hot / log- apply-result.js 1.27 KiB {main} [内置] [./src/index.js] 177字节{main} [内置] + 26个隐藏模块
../ common / form_builder / src / index.js中的错误 模块构建失败(来自./node_modules/babel-loader/lib/index.js): 语法错误:/Users/cmc/Sites/common/form_builder/src/index.js: 意外令牌(7:12)
5 | render() {
6 | return(
7 | <div>
| ^
8 | Test
9 | </div>
10 | )
在Parser.raise(/ Users / cmc / Sites / webpack- 测试/node_modules/@babel/parser/lib/index.js:6322:17) 在Parser.unexpected(/ Users / cmc / Sites / webpack- test/node_modules/@babel/parser/lib/index.js:7638:16)