将Babel与JavaScript结合使用 [英] Use Babel with JavaScript

查看:93
本文介绍了将Babel与JavaScript结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写我的第一个babel程序,有点卡住了.

I am trying to write my first babel program and kind of stuck.

var message = "Hello World";
module.exports = message;

和script2

var message = require('./script1');
document.write(`This is formatted with ES6 ${message}`);

我的webpack.config.js看起来像

module.exports = {
    entry: {
         main: [
            './script1.js',
            './script2.js'
        ]
    },
    output: {
        filename: "./public/[name].js"
    },
    loaders: {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel'
    }
}

上面的代码有效,我能够看到输出,但是现在如果我将script2修改为

The above code works and I am able to see the output but now if I modify script2 to

import message from './script1';
document.write(`This is formatted with ES6 ${message}`);

然后当我运行webpack时说

then when I run webpack it says

ERROR in ./script2.js
Module parse failed: /Users/a.c/MyProjects/ReactTutorial/script2.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import message from './script1';
| document.write(`This is formatted with ES6 ${message}`);
 @ multi main

我的理解是,因为我正在使用babel,所以我应该能够使用新的ES6方法轻松地将内容导入代码中.

My understanding is that because I am using babel, I should be able to use the new ES6 way of importing stuff into my code easily.

推荐答案

您很可能忘记了指定

Most likely you have forgotten to specify es2015 preset for babel.

  1. 确保已安装:

  1. Make sure it's installed:

> npm i -D babel-preset-es2015

  • 您有两个选项可以为babel指定此预设.

  • You have two options to specify this preset for babel.

    1. 创建.babelrc文件并在其中指定预设:

    1. Create .babelrc file and specify the preset there:

    {
        "presets": ["es2015"]
    }
    

  • 使用 query属性指定预设:

  • Specify the preset using query property:

    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          include: /src/,
          loader: 'babel',
          query: {
            presets: ['es2015']
          }
        }
      ]
    }
    

  • 这篇关于将Babel与JavaScript结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆