node.js - 使用 babel 转译时删除 module.exports 声明

标签 node.js babeljs

有没有办法在使用 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/

相关文章:

javascript - 如何使用 mysql 数据库在 node.js 中制作登录表单

node.js - HTTP 代理 (Node.js) 未执行正确的 SSL 验证

babeljs - Aurelia 模块中 @ 错误处的意外 token

node.js - 编写 ES6 代码时如何使用 Babel 将 Node.js/React 应用程序部署到 Heroku?

javascript - 另一个文件夹中的 Node_modules

javascript - 为什么 HTML 验证在 Electron 中不起作用?

javascript - 自定义模块express js :Cannot find module name error when modules folder in root directory

node.js - 如何在docker中安装nvm?

javascript - 导入不适用于 babel 和 webpack

babeljs - String.prototype.includes未转换为ES5