Import React from 'react' results in Uncau

2020-04-04 07:53发布

问题:

I've installed webpack 3 along with babel and my entry index.js/bundle.js will build and run, which I've tested with ES7/8 features, however imports won't work and result in Uncaught SyntaxError: Unexpected identifier. I've tried putting the babel config in the package.json as well as in a separate .babelrc file in my app root directory but I still get the error when trying to import. Am I missing a package or setting?

index.js (works)

// does not work
// import React from 'react' 

// works
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));

webpack.config.js

const path = require('path')

module.exports = {
  context: path.resolve(__dirname, 'app/assets/javascripts/source'),
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'app/assets/javascripts/webpack')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
}

.babelrc

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

package.json

}
  ...
  "license": "MIT",
  "scripts": {
    "build": "webpack",
  },
  "babel": {
    "presets": [
      "env",
      "react"
    ]
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.11.1"
  }
}

回答1:

Try this : transform-es2015-modules-amd , This plugin transforms ES2015 modules to Asynchronous Module Definition (AMD).

{
    presets: ["env", "react"],
    plugins: ["transform-es2015-modules-amd"]
 }

more at transform-es2015-modules-amd



回答2:

It is not working because it is not translating es6, so import statement is not working, Yo need to babel-preset-es2015

and configure it .babelrc

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