有没有办法在使用 Babel 转译时删除 module.exports 声明?我正在使用 module.exports 进行测试 (Jest),但我不希望这些导出将其添加到生产文件中。
例如,如果我有以下 js 文件,我想使用 Babel 进行转译:
function sum(a, b) {
return a + b;
}
module.exports = sum;
如何从转译版本中删除 module.exports = sum;
?
最佳答案
我今天遇到了同样的问题,我使用 gulp 作为解决方案: 在你的 gulpfile.babel.js 中添加一个过滤器,使用如下正则表达式模式从你的 js 文件中删除你想要的任何内容:
const compiledDir = './src/compiled';
// Lines that you want to remove in this case you have two.
const filters = [
/^"use strict";/,
/^module.exports = parseSiteSectionName;/
];
// then add a task into the same file that uses the filter:
gulp.task('build-sum', () => {
let buildResult = browserify({ debug: false })
.transform(babelify)
.require(`./src/sum.js`, { entry: true })
.bundle()
.on('error', (err) => { console.log('Error: ' + err.message); })
.pipe(source('sum.js'))
.pipe(buffer())
.pipe(template({ env }))
// Remove lines that are in your filter
.pipe(removeLines({ filters: filters }));
buildResult = buildResult
.pipe(jsEscape({
omitDelimiters: true
}))
.pipe(gulp.dest(compiledDir));
return buildResult;
});
关于node.js - 使用 babel 转译时删除 module.exports 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530314/