问题
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