出于某种原因,我似乎无法让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'));
答案 0 :(得分:10)
我让你的设置正在进行这些修改。我将问题隔离到您的测试属性。
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']
},
}
]
}
};
答案 1 :(得分:2)
原因可能是
import Example from './Example'
index.jsx
webpack会将此视为js
导入,而不是jsx
。
试
import Example from './Example.jsx'