背景
我正在使用 React、babel、webpack4 和 es6(或者可能是 es7)
我有一些模块被多个反应项目重用。因此,我创建了一个包含这些模块的“标准”文件夹,以便它们与任何特定项目分开。
Problem
在我的 React 项目中,我编辑了 webpack.config.js 以包含
resolve: {
extensions: ['.css', '.js', '.jsx'],
alias: {
Standard: '/Path/To/Standard',
}
}
然后要从中导入模块,我调用
import MyModule from 'Standard/MyModule.js'
当我这样做时,我的标准文件夹中的文件似乎无法识别 html 标签
错误信息
For webpack-dev-server --inline
ERROR in /Path/To/Standard/MyModule.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Path/To/Standard/MyModule.js: Unexpected token (13:8)
11 | var MyModule = (props) => {
12 | return (
> 13 | <header id='Header' className={props.className}>
For webpack
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] /cdn-cgi/l/email-protection build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] /cdn-cgi/l/email-protection build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
调试尝试
我尝试在我的标准文件夹(除了我的项目文件夹之外)中创建 webpack.config.js 和 package.json,但似乎没有任何帮助
我尝试了一些 npm installs 来安装 babel,因为这似乎是最明显的解决方案,并在较旧的 webpack 版本中用于此答案 https://stackoverflow.com/questions/20905227/reactjs-unexpected-token-error,但我仍然遇到同样的问题
npm install --save react
npm install --save babel @babel/cli @babel/core @babel/preset-env @babel/preset-react
npm install --save babel-core babel-loader babel-cli babel-preset-env babel-preset-react webpack
也看起来像这个帖子 https://medium.com/@frewin.christopher/update-for-2018-for-anyone-else-running-into-errors-that-webpack-was-complaining-about-the-jsx-18dd5447bcd1这是对这个博客 https://medium.com/@BrodaNoel/how-to-create-a-react-component-and-publish-it-in-npm-668ad7d363ce可能相关,但这个解决方案对我不起作用。
包.json
{
"scripts": {
"webpack": "webpack",
"start": "http-server"
},
"dependencies": {
"react": "^16.8.6"
},
"devDependencies": {
"@babel/cli": "^7.5.5",
"@babel/core": "^7.5.5",
"@babel/plugin-proposal-object-rest-spread": "^7.5.1",
"@babel/polyfill": "^7.4.4",
"@babel/preset-env": "^7.5.0",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"webpack": "^4.28.0"
}
}
webpack.config.js
var webpack = require('webpack');
const config = {
mode: 'development', // set mode option, 'development' or 'production'
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
},
resolve: {
extensions: ['.css', '.js', '.jsx'],
}
}
module.exports = config;
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": [
[
"@babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}