How to transpile node_modules folder using just babel 7?

99封情书 提交于 2020-06-12 06:36:27

问题


Trying to unit test reactjs application using mocha but getting error from es6 features (import/export) used inside node_modules folder. The application in question is transpiled using babel but since one of react component is using a module from node_modules its throwing error Syntax Error:Unexpected token export. I am aware that babel ignores node_modules folder by default, but not sure how to approach this. Any help would be appreciated. Thanks.

Test Command :-

  "test": "SET NODE_ENV=test&& mocha --require @babel/register --require ignore-styles -r jsdom-global/register \"./src/**/*.test.js\"",

babel.config.js :-

module.exports = function (api) {
  const presets = ["react-app"];
  const plugins = [
      "@babel/plugin-transform-modules-commonjs", 
      "inline-react-svg"
  ];
  const ignore = [/node_modules/]
  api.cache(false); 
  return {
      presets, 
      plugins,
      ignore
  }
};

回答1:


Got it working!. Had to switch from Mocha to Jest since I was using react-app-rewired which was internally configured to use Jest. A small change in config-override.js was needed. Added a jest config with "transformIgnorePatterns": ["node_modules/(?!MODULES_TO_BE_TRANSPILED)"]. Hope it helps others.




回答2:


try this command, you need to pass ignored directories in command line with --ignored option.

./node_modules/.bin/babel . -d ~/app_compressed/ --ignore node_modules,test,assets,stuff,views,public,test,spec,logs,lib/jasmine_examples,db,routes/api/drafts,**/drafts

Also, make sure to use a babel.config.js file instead of a .babelrc file. so the config file will look like following.

module.exports = function (api) {
    api.cache(true);
    return {
        babelrcRoots: [
            '.',
            './modules/*'
        ],
    ignore: [/node_modules/],
    presets: ["@babel/preset-env"]
    };
}


来源:https://stackoverflow.com/questions/57287874/how-to-transpile-node-modules-folder-using-just-babel-7

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