出于某种原因,我似乎无法让 Webpack 从 .JSX 文件导入模块。每次我尝试运行 Webpack 时,我都会收到以下消息:
ERROR in ./src/Example.jsx
Module parse failed: /path/to/project/src/Example.jsx Unexpected token (6:12)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (6:12)
事情是; ./src/Example.jsx 中没有太多内容。事实上,这就是它包含的全部内容:
import React from 'react';
export default class Example extends React.Component{
render() {
return (<h2>Hello world!!</h2>);
}
};
当我将类放在我的index.jsx文件中时,Webpack没有任何问题,但是当我将它移动到它自己的文件时,webpack突然不知道该怎么做。我尝试使用 babel-plugin-transform-react-jsx 来解决此问题但这似乎并没有解决我的问题。我需要做什么才能让 Webpack 正确转换/解析 .JSX 文件?
/* package.json */
{
...,
"dependencies": {
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"webpack": "1.13.1"
},
"devDependencies": {
"concurrently": "^2.2.0",
"eslint": "^3.1.1",
"eslint-plugin-react": "^5.2.2",
"jest-cli": "^13.2.3",
"react-addons-test-utils": "^15.2.1",
"webpack-dev-server": "^1.14.1"
},
"scripts": {
"build": "webpack -p",
"dev": "webpack-dev-server --port 9999",
"start": "npm run build && python -m SimpleHTTPServer 9999",
"test": "jest --verbose --coverage --config jest.config.json"
}
}
/* webpack.config.js */
var path = require('path');
var webpack = require('webpack');
var BUILD_DIR = path.resolve(__dirname, 'build/');
var SOURCE_DIR = path.resolve(__dirname, 'src/');
module.exports = {
entry: SOURCE_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /[^\.spec]+\.jsx$/,
include: SOURCE_DIR,
loader: 'babel'
}
]
}
};
/* .baberc */
{
"presets": ["es2015", "react"]
}
/* src/index.jsx */
import React from 'react'
import ReactDOM from 'react-dom';
import Example from './Example'
ReactDOM.render(<Example />, document.getElementById('floor-plan'));
最佳答案
我通过这几个修改让你的设置正常工作。我将问题隔离到您的测试属性。
var path = require('path');
var webpack = require('webpack');
var BUILD_DIR = path.resolve(__dirname, 'build/');
var SOURCE_DIR = path.resolve(__dirname, 'src/');
module.exports = {
entry: SOURCE_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: SOURCE_DIR,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
},
}
]
}
};
关于reactjs - ES6 无法在 Webpack 中导入 JSX 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38529554/