babel-plugin-语法-动态导入不会转换

时间:2018-08-14 13:11:12

标签: reactjs webpack babel

我认为我已经正确配置了babel-plugin-syntax-dynamic-import,但是它仍然不能转换我的动态导入。

节点:v8.11.3

package.json:

  ...
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-loader": "^7.1.5",
    "babel-plugin-syntax-dynamic-import": "^6.18.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    ...
    "webpack": "^4.16.5",
    "webpack-bundle-analyzer": "^2.13.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
  },
  "scripts": {
    "dev": "webpack-dev-server --config webpack.config.js --open --hot --progress",
  ...
  },

  "dependencies": {
    "babel-core": "^6.26.3",
    "babel-polyfill": "^6.26.0",
    ...
    "react-loadable": "^5.5.0",
    "whatwg-fetch": "^2.0.4"
  }

webpack.config.js:

...
{
  test: [/\.js$/, /\.jsx?$/],
  exclude: /node_modules/,
  use: {
    loader: 'babel-loader',
  },
},
...

.babelrc

{
  "presets": ["env", "react", "stage-3"],
  "plugins": ["syntax-dynamic-import"]
}

AsyncComp.jsx:

import React from 'react';
import Loadable from 'react-loadable';

const Loading = () => (<div>Loading...</div>);

const LoadableComponent = Loadable({
  loader: () => import('./CompRaw'),
  loading: Loading,
})

export default class AsyncComp extends React.Component {
  render() {
    return <LoadableComponent />;
  }
}

执行yarn dev会导致:

/home/somepath/src/components/AsycnComp.jsx
  7:17  error  Parsing error: Unexpected token import

为什么动态import()没有被转译?我该如何解决?

2 个答案:

答案 0 :(得分:3)

好吧!我认为您也需要react-loadable/babel。请参阅此处的讨论:https://github.com/jamiebuilds/react-loadable/pull/35#issuecomment-337156641

答案 1 :(得分:1)

配置良好,错误是由于使用eslint-loader而未安装babel-eslint插件引起的,该插件将支持动态导入。

这解决了问题

yarn add babel-eslint -D

.eslintrc

{
  ...
  "parser": "babel-eslint"
}