目前我的webpack脚本版本中有两个文件, script.js 和 contact-menu.js 。如果我在主 script.js 文件上创建反应组件,则会转换为ok。如果在 contact-menu.js 中创建React组件并尝试导出导入,则会出现以下错误:
> ERROR in ./babel/contact-menu.js Module parse failed:
> /Applications/MAMP/htdocs/mcdonalds excavation/themes/mcdonalds/babel/contact-menu.js
> Unexpected token (7:3) You may need an appropriate loader to handle
> this file type. | render(){ | return( | <div
> id="contact-menu-container"> | <div id="contact-menu-btn"> |
> Close @ ./babel/script.js 11:19-47
我尝试将文件从js重命名为jsx,以及更改webpack config上的入口点
webpack config
var path = require('path');
var debug = process.env.NODE_ENV !== 'production';
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? 'inline-sourcemap' : null,
entry: './babel/script.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'script.js'
},
module: {
loaders: [{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
include: [path.resolve(__dirname, 'babel/script.js')],
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-3'],
plugins: ['transform-react-jsx']
}
}, {
test: /\.scss$/,
include: [path.resolve(__dirname, 'sass')],
loaders: ['style-loader', 'css-loader', 'sass-loader']
}, {
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file-loader"
}]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: false,
sourcemap: false
}),
],
};
的package.json
{
"name": "react-kit",
"version": "3.0.0",
"description": "React Build Kit With Webpack.",
"main": "webpack.config.js",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"axios": "^0.15.3",
"babel-cli": "^6.18.0",
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-plugin-transform-react-jsx": "^6.8.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-3": "^6.5.0",
"css-loader": "^0.26.1",
"fetch-jsonp": "^1.0.6",
"history": "^1.17.0",
"node-sass": "^4.5.0",
"react-router": "^3.0.1",
"sass-loader": "^5.0.1",
"style-loader": "^0.13.1",
"webpack": "^2.2.1",
"webpack-dev-server": "^1.14.1"
},
"author": "",
"license": "MIT"
}
script.jsx
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(
<ContactMenu />,
document.getElementById('contact-menu')
)
与-menu.jsx
import React from 'react'
import ReactDOM from 'react-dom'
export default class ContactMenu extends React.Component{
render(){
return(
<div id="contact-menu-container">
<div id="contact-menu-btn">
Close
</div>
<div id="contact-menu">
</div>
</div>
)
}
}
答案 0 :(得分:1)
我相信你的webpack配置中的这一行是问题所在:
include: [path.resolve(__dirname, 'babel/script.js')],
webpack documentation相当稀疏,但似乎如果指定include
,则加载器只会转换其中的路径。如果省略该选项,则test
中列出的{{1>}并且未列在exclude
中的所有路径都应由加载程序转换,包括contact-menu.js
。< / p>