因為項目需要搞一下按需加載,使用import實現代碼打包分片按需加載,但是在實際使用中報語法錯誤。報錯信息如下
SyntaxError: ‘import’ and ‘export’ may only appear at the top level
啊咧?報錯了。
查找發現很多人碰到過,解決方法不同,但是我這個報錯適用下邊這個方法。
npm install --save-dev babel-plugin-syntax-dynamic-import
然后調整babel-loader配置如下:
use: { loader: 'babel-loader', options: { // 不采用.babelrc的配置 "babelrc": false, "presets": [ ["react"], ["es2015", { "modules": false }] ], "plugins": [ "syntax-dynamic-import", "transform-object-rest-spread", "transform-class-properties" ] } }
//解決方法出處示下邊這篇博文:
http://www.shuizhongyueming.com/2017/11/28/webpack-dynamic-import%E5%87%BA%E9%94%99-syntaxerror-import-and-export-may-only-appear-at-the-top-level/
為防止博客哪天不用了,整篇文章轉載過來。以下示原博文。
起因
今天嘗試使用webpck的import()
來做代碼分割。
代碼類似如下:
import('./nice-scroll').then(init => init(dom))
結果報錯:
ERROR in ./js/utils/auto-set-height.js
Module build failed: SyntaxError: ‘import’ and ‘export’ may only appear at the top level (20:8)
分析
在package.json里面確認了一下,我用的webpack版本是^3.5.4
,這個是一定支持import()方法的,那么問題應該就出在babel上了。
先截取我的babel-loader
的部分配置:
use: { loader: 'babel-loader', options: { // 不采用.babelrc的配置 "babelrc": false, "presets": [ ["react"], ["es2015"] ], "plugins": [ "transform-object-rest-spread", "transform-class-properties" ] } }
一開始我的猜想是plugin es2015
里面的transform-es2015-modules-commonjs
先於webpack處理了代碼,所以報錯。
找了一下禁用的方法,改配置如下:
use: { loader: 'babel-loader', options: { // 不采用.babelrc的配置 "babelrc": false, "presets": [ ["react"], ["es2015", {module: false}] ], "plugins": [ "transform-object-rest-spread", "transform-class-properties" ] } }
還是不行。
后面一直各種關鍵詞的搜索,偶然在github上面找到這個問題Dynamic `import()` crashing in `ModuleConcatenationPlugin`的一個回答:
Nope; babel will always process the code before webpack ever sees it; unless for some reason the file itself is being excluded from being processed by babel-loader.
This error is unrelated to babel; it’s a webpack issue.
這個回答,里面說到在webpack面對的代碼都是babel處理過的,這個讓我堅信問題還是在babel這塊,繼續搜索。
意外找到這個這篇文章:代碼分離 – 使用import()。里面說到了一個插件:syntax-dynamic-import
Babel官方關於這個插件的描述是:
Syntax only
This plugin only allows Babel to parse this syntax. If you want to transform it then see dynamic-import-webpack or dynamic-import-node.
顯然這是一個語法解析的插件,使得babel能夠理解dynamic import的語法。再聯系上面的報錯信息里面的SyntaxError,結果有點明顯了。
解決
npm install --save-dev babel-plugin-syntax-dynamic-import
然后調整babel-loader配置如下:
use: { loader: 'babel-loader', options: { // 不采用.babelrc的配置 "babelrc": false, "presets": [ ["react"], ["es2015", { "modules": false }] ], "plugins": [ "syntax-dynamic-import", "transform-object-rest-spread", "transform-class-properties" ] } }
重啟webpack,順利通過編譯!!!