How do you use es6 promises today on frontend?

前端 未结 3 730
庸人自扰
庸人自扰 2021-01-02 14:47

I\'m trying to use babel to compile file that contains es6 promises. I have installed babel-cli, babel-preset-es2015, babel-plugin-es6-promise.

My .babelrc config i

3条回答
  •  死守一世寂寞
    2021-01-02 15:14

    Babel itself is just a transpiler, it translates from ES6 to ES5, and nothing else. Since ES6 includes modules, which can be used for imports like:

    import Awesome from './Awesome'
    

    Babel will transpile that into require statements for you, but not care about the actual requiring. Therefore you need any framework that implements the AMD style require, like Browserify or something like that. Webpack will also handle that for, so if you use Webpack + Babel, all the required code will be available and there is nothing in your way to use ES6 modules (and Promises, too) via the new import statement.

    I am using a webpack.config.js like that:

    module.exports = {
        entry: ['babel-polyfill', './js/main.js'],
        output: {
            path: './bin/js',
            filename: 'main.js',
        },
    
        devtool: 'source-map',
    
        module: {
            loaders: [{
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
        }]
      }
    }
    

    and a .babelrc like that:

    { 
        "presets": [ "es2015", "stage-3" ],
        "plugins": [
            "external-helpers",
            "transform-async-to-generator",
            "transform-runtime"
        ]
    }
    

    Before I started to use Webpack, I used Gulp and browserify, to first compile and than to bundle, but the setup with webpack is much simpler, so I decided to use that…

提交回复
热议问题