Still receive syntax error for dynamic import with

2019-05-27 17:16发布

问题:

All babel modules/plugins are on the latest version of babel v6. Mocha is on v4.0.1.

Setup:

// .babelrc
{
   presets: [
      "stage-3",
      [
         "env",
         {
           "targets": {
              "browsers": [
                "last 2 versions"
              ],
              "node": "current"
           }
         }
      ]
      "react"
   ],
   plugins: ["transform-runtime", "syntax-dynamic-import"]
}


// mocha.opts
--recursive
--reporter progress
--require babel-polyfill
--require babel-register
--timeout 20000

So when I run my test suite I still get: error stack trace.

I would have to imagine it has something to do with babel-register and syntax-dynamic-import not working together correctly. Because when I use it with babel-loader in webpack I don't get any syntax errors on transpile.

回答1:

This answer on babeljs slack from Satyajit Sahoo cleared things up for me:

syntax-dynamic-import will only enable the syntax in babylon, which means it babylon can parse the code without syntax error. the code import(...) is still there, which node doesn’t understand and you still need to transpile it. dynamic-import-node transpiles the import(...) to require which node understands. On client, the transpilation step is not necessary since Webpack understands the syntax and does the bundling.