【问题标题】:How to solve the error: SyntaxError: Unexpected token import如何解决错误:SyntaxError: Unexpected token import
【发布时间】:2023-04-11 05:00:01
【问题描述】:

之前遇到过这个错误,看到了其他答案,但是解决方案并没有解决我的问题。

在我的 package.json 中有:

 "dependencies": {
    "axios": "^0.15.2",
    "babel": "^6.5.2",
    "babel-core": "^6.13.1",
    "babel-loader": "^6.0.1",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-node5": "^11.1.0",
    "babel-preset-react": "^6.0.15",
    "babel-preset-stage-0": "^6.0.15",
    "babel-preset-stage-2": "^6.11.0",

然后在我的 webpack.config.js 我有:

module.exports = {
 entry: './main.js',

然后在我的 main.js 中我有:

import "./src";

然后我运行 npm test 调用此脚本:

 "scripts": {
    "test": "mocha src/**/*.spec.js",

然后它失败了,因为在 src/components/header/index.spec.js:1 我有:import React from 'react';

不知道为什么它不起作用

我有一个.babelrc 文件,其中包含:

{
  "sourceMaps": true,
  "presets": ["es2015", "react", "stage-2"]
}

在我的 webpack 中我也有:

module: {
   loaders: [
     {
       test: /\.js$/,
       exclude: /node_modules/,
       loader: 'babel',
       query: {
         presets: ['es2015', 'react', 'stage-2']
       }
     },
     {
        test: /\.scss$/,
        loaders: ["style-loader", "css-loader", "sass-loader"]
      }
   ]
 }

有什么想法吗?

【问题讨论】:

    标签: javascript node.js reactjs import babeljs


    【解决方案1】:

    你可以去 babel 设置页面并选择你的测试框架,然后它会帮助你逐步将测试框架与babel 集成。可能是你的测试脚本写这个:

    "mocha --compilers js:babel-register src/**/*.spec.js"

    【讨论】:

    • 首先看到了另一个答案,所以投了票,但会投赞成票,谢谢
    【解决方案2】:

    当你通过 mocha 命令执行测试时,它会在没有 ES6 的情况下在 node.js 中执行你的测试脚本,因为 V8 还没有实现 ES6。

    您可以使用 mocha 的编译器。你有 babel-core,你可以使用这个命令(在你的情况下更好):

    mocha src/**/*.spec.js --compilers js:babel-core/register
    

    或者单独安装 babel-register(babel-register 模块)并使用:

    mocha --compilers js:babel-register
    

    查看更多:http://jamesknelson.com/testing-in-es6-with-mocha-and-babel-6/

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2016-10-04
      • 1970-01-01
      • 2017-12-30
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多