使用了webpack,babel 但是不知为什么我一旦import 文件就会报错!而且ES6的语法也不能用!

williamstar
  • 137

我的webpack配置

var ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
    entry: './src/main.js',
    output: {
        path: './build',
        publicPath:'/build/',
        filename: 'build.js'
    },
    module: {

        loaders: [
            {
                test: /\.vue$/,
                loader: 'vue'
            },
            {
                test: /\.js$/,
                loader: 'babel',
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif)$/,
                loader:'url?limit=8192',
            },
            {
                test: /\.scss$/,
                loader: 'style!css!sass'
            }
        ]
    },
    vue:{
      loaders:{
          css: ExtractTextPlugin.extract('css'),
          sass: ExtractTextPlugin.extract('css!sass')
      }  
    },
    plugins: [
        new ExtractTextPlugin('./app.css')
    ]
}

我的package.json文件

"devDependencies": {
    "babel-core": "^6.6.4",
    "babel-loader": "^6.2.4",
    "babel-plugin-add-module-exports": "^0.1.1",
    "babel-plugin-transform-runtime": "^6.6.0",
    "babel-polyfill": "^6.6.1",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-es2015-rollup": "^1.1.1",
    "babel-preset-stage-2": "^6.5.0",
    "babel-runtime": "^5.8.0",
    "bootstrap": "^3.3.6",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.8.5",
    "node-sass": "^3.4.2",
    "template-html-loader": "0.0.3",
    "url-loader": "^0.5.7",
    "vue-hot-reload-api": "^1.3.2",
    "vue-html-loader": "^1.2.0",
    "vue-loader": "^8.2.0",
    "vue-style-loader": "^1.0.0",
    "webpack": "^1.12.14",
    "webpack-dev-server": "^1.14.1"
  },
  "dependencies": {
    "highlight.js": "^9.2.0",
    "marked": "^0.3.5",
    "vue": "^1.0.17",
    "vue-resource": "^0.7.0",
    "vuex": "^0.4.2"
  }

import代码

import store from './vuex/store'
import 'babel-polyfill'
var Vue = require('vue')

报错代码

ERROR in ./src/main.js
Module parse failed: d:\nodejs\wp\node_modules\babel-loader\index.js!d:\nodejs\wp\src\main.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import 'babel-polyfill';
| import Vue from 'vue';
@ multi main

如果要使用我只能使用require的语法,但是我必须使用import的来导入一些东西,而且我的ES6语法根本不能使用,求大家帮忙下!

回复
阅读 18.4k
3 个回答
李若炎
  • 1.4k
✓ 已被采纳

是不是因为babel没有加query的原因呢。babel你是用了,但是你没有指定你用babel解析什么语法啊。加上一个query:{presets: ['es2015']} ,在这之前你要先install babel-preset-es2015

推荐先看看babel官网和相关loader和plugin的使用方式。
这个主要原因在于babel-loader插件的使用方式,你需要对此插件进行参数配置,通常有两种方式:

  1. 直接写在webpack配置代码里:
{
    test: /\.js$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    options: {
      cacheDirectory: true,
      presets: [['env', { modules: false }], 'stage-2'],
    },
}
  1. 在根目录创建.babelrc配置文件
{
  "presets": ["stage-2"]
}

当然别忘记安装相关插件,比如上面使用的 babel-preset-stage-2,这里stage2表示 完成初步规范的语法,包括目前流行的es6风格语法

宣传栏