简体   繁体   中英

Node Webpack not recognizing “Import”

So I'm new to Node and Webpack, and I'm having trouble getting my project to compile correctly. Every time I load it into the browser I get the error: Uncaught SyntaxError: Unexpected token import . Here's a copy of my webpack.config.js file:

webpack.config.js:

var path = require('path');
var webpack = require('webpack');

var loaders = [
  {
    "test": /\.js?$/,
    "exclude": /node_modules/,
    "include": ["/js","/src", "/build"],
    "loader": "babel",
    "query": {
      "presets": [
        "es2015",
        "react",
        "stage-0"
      ],
      "plugins": []
    }
  }
];

module.exports = {
  devtool: 'eval-source-map',
  entry: path.resolve('js', 'main.js'),
  output: {
    path: path.resolve('build'),
    filename: '[name].js',
    publicPath: '/'
  },
  plugins: [],
  module: {
    loaders: loaders
  }
};

And here's a copy of my main.js file:

main.js

import React from 'react';
import {render} from 'react-dom';

And finally, here's a list of my installed node packages:

  • babel-core
  • babel-loader
  • babel-preset-es2015
  • babel-preset-react
  • babel-preset-stage-0
  • babelify
  • react
  • react-dom
  • webpack
  • webpack-dev-server

Does anyone know what I'm doing wrong? Thanks for your help!

The exclude and include settings expect either a RegExp, an absolute path or an array of these. Your example sets the include property to an array of strings. What you need instead is an array of RegExp:

include: [/.js?$/, /src/, /build/]

The first parameter matches a us file and the latter two match the src and build folders respectively.

Notice how I've omitted the speech marks around the object properties. In addition I'd also just nest the loader contents within module.exports instead of separating it out but for the sake of argument I shall edit in situ:

var loaders = [
  {
    test: /\.js?$/,
    exclude: /node_modules/,
    include: ["/.js?&/","/src/", "/build/"],
    loader: "babel",
    query: {
      presets: [
        "es2015",
        "react",
        "stage-0"
      ],
      plugins: []
    }
  }
];

module.exports = {
  devtool: 'eval-source-map',
  entry: path.resolve('js', 'main.js'),
  output: {
    path: path.resolve('build'),
    filename: '[name].js',
    publicPath: '/'
  },
  plugins: [],
  module: {
    loaders: loaders
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM