2016-11-30 20 views
0

我試圖讓webpack解析一個使用新的異步/等待語法的javascript文件,但它一直給我一個解析錯誤。使用webpack解析異步函數的問題

這裏是我的webpack.config.js文件:

module.exports = { 
    entry: { 
    foo: './foo.js' 
    }, 
    output: { 
    filename: 'webpack-compiled.js' 
    }, 
    module: { 
    loaders: [ 
     { 
     test: /\.js$/, 
     loader: 'babel-loader', 
     exclude: /node_modules/ 
     } 
    ] 
    } 
} 

我的package.json文件:

{ 
    "name": "async-func-test", 
    "version": "1.0.0", 
    "description": "", 
    "main": "foo.js", 
    "scripts": { 
    "buildWithBabel": "babel foo.js --out-file babel-compiled.js", 
    "buildWithWebpack": "webpack --progress --colors" 
    }, 
    "author": "", 
    "license": "ISC", 
    "devDependencies": { 
    "babel-cli": "^6.18.0", 
    "babel-core": "^6.18.2", 
    "babel-loader": "^6.2.8", 
    "babel-plugin-syntax-async-functions": "^6.13.0", 
    "webpack": "^1.13.3" 
    } 
} 

我babel.rc文件:

{ 
    "plugins": [ 
    "syntax-async-functions" 
    ] 
} 

而FOO .js文件:

async function asyncFunc() { 
    return 123 
} 

asyncFunc().then(x => console.log(x)) 

如果我運行npm腳本'buildWithBabel',它運行良好,沒有錯誤,並創建了正確輸出的babel-compiled.js。

但是,如果我跑故宮腳本「buildWithWebpack」,我得到了以下錯誤消息:

ERROR in ./foo.js 
Module parse failed: C:\Users\Redark\Desktop\asyncFuncTest\node_modules\babel-loader\lib\index.js!C:\Users\Redark\Desktop\asyncFuncTest\foo.js Unexpected token (1:6) 
You may need an appropriate loader to handle this file type. 
SyntaxError: Unexpected token (1:6) 

我不需要改造異步功能,只是對其進行分析。我不知道爲什麼它不適用於webpack,因爲它應該使用.babelrc中的「syntax-async-functions」插件?

回答

0

您還需要使用transform-regenerator pluginsyntax-async-functions只允許Babel解析輸入(然後保持獨立)。 Webpack並不理解ES8語法,這就是爲什麼它沒有經過轉換就失敗了。