babel 7 don't compile class ES6 which in node_modules

别等时光非礼了梦想. 提交于 2019-12-22 04:18:14

问题


I have error in IE11 SCRIPT1002: Syntax error (problem with class syntax). My simple code with 2 lines:

import { struct } from 'superstruct';
console.log('finished');

I wan't that my babel7 compile class into ES5 code

I have tried write .babelrc file :

 {
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "ie": "11"
        }
      }
    ]
  ]
}

and https://babeljs.io/docs/en/babel-plugin-transform-classes haven't fixed too

Update : I have tried use @babel/plugin-preset-es2015 which convert class in ES5 code but this package is deprecated in babel7

Help me please


回答1:


In order to transform node_modules and child packages in Babel 7 you need to use a babel.config.js file instead of a .babelrc file.

See this issue comment and the babel documentation on project-wide configuration. Specifically

New in Babel 7.x, Babel has as concept of a "root" directory, which defaults to the current working directory. For project-wide configuration, Babel will automatically search for a "babel.config.js" in this root directory.

...

Because project-wide config files are separated from the physical location of the config file, they can be ideal for configuration that must apply broadly, even allowing plugins and presets to easily apply to files in node_modules or in symlinked packages, which were traditionally quite painful to configure in Babel 6.x.

The short of it is that .babelrc is used for a local project file transformations (not including node_modules) while babel.config.js should be considered project-wide and will apply to package dependencies when bundling (node_modules). It's a bit confusing but hopefully that helps!

Edit

Here's a bit more information on a full project config to build your example file using webpack. Note that if you use .babelrc instead of babel.config.js here it will not work. Running webpack-cli produces a script script.out.js that does not use the class keyword.

script.js
import { struct } from 'superstruct';
console.log('finished');
babel.config.js
module.exports = {
    "presets": [
        [
            "@babel/preset-env",
            {
                    "targets": {
                    "ie": "11"
                }
            }
        ]
    ]
};
webpack.config.js
module.exports = {
    entry: './script.js',
    output: {
        path: __dirname,
        filename: 'script.out.js',
    },
    module: {
        rules: [ {
            test: /\.m?js$/,
            use: {
                loader: 'babel-loader'
            }
        } ]
    }
}
Package Dependencies
"@babel/core": "^7.3.4",
"@babel/preset-env": "^7.3.4",
"babel-loader": "^8.0.5",
"superstruct": "^0.6.0",
"webpack-cli": "^3.2.3"


来源:https://stackoverflow.com/questions/54788809/babel-7-dont-compile-class-es6-which-in-node-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!