Babel-register没有转发与Webpack的React

时间:2018-03-10 11:14:35

标签: javascript reactjs webpack babeljs babel-register

我试图在我的webpack配置中使用babel-register。这是我的文件:

.babelrc

{"presets": ["react","env"]}

webpack.config.js。

const path = require('path');

module.exports = {

    entry: {
        'app' : './src/app.jsx'
    },

    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },

    devServer: {
        contentBase: './dist',
        open: true
    }

};

的package.json。

{
  "name": "react-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "node -r babel-register ./node_modules/webpack/bin/webpack.js",
    "debug": "node -r babel-register ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.2.0",
    "react-dom": "^16.2.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "babel-register": "^6.26.0",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.10",
    "webpack-dev-server": "^3.1.1"
  }
}

输出错误是:

ERROR in ./src/app.jsx
Module parse failed: Unexpected token (5:2)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
|   <h1>Hello, world!</h1>,
|   document.getElementById('root')
| );
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/app.jsx
i 「wdm」: Failed to compile.

我不明白为什么,使用节点和babel-register模块启动webpack,最后一个不会转换遇到的所有子序列文件。 我知道使用webpack模块转换.js,.jsx会更好,但我想在此repo中模拟调试和生产模式的示例:https://github.com/chentsulin/electron-react-boilerplate 谢谢你的答案。

1 个答案:

答案 0 :(得分:0)

babel-register需要在源文件的上下文中导入,而不是webpack。运行webpack时需要它会传输webpack的代码,但不是你自己的代码。

一种方法是创建另一个文件,例如main.js,然后导入babel-register,然后输入你的app条目,并将webpack条目指向:

import 'babel-register'
import './app.jsx'

另一种更简单的方法是将babel-register添加到webpack配置中的app条目中,如下所示:

'app': ['babel-register', './src/app.jsx']