删除捆绑包死代码

Removing bundle dead code

我正在使用带有 CommonJs 的 browserify。

我有这个结构的文件 2。

module.exports = {
  value: 'bling bling'
};

我有这个结构的文件 1。

var file2 = require('./file2.js');

console.log('this is the file 2 object value', file2.value);

所以我在我的终端运行下面的命令

$ browserify -g uglifyify ./file1.js | uglifyjs -c > bundle.js

捆绑结果将是。

!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var file2=require("./file2.js");console.log("this is the file 2 object value",file2.value)},{"./file2.js":2}],2:[function(require,module,exports){module.exports={value:"bling bling"}},{}]},{},[1]);

我想知道是否有机会通过任何转换为​​我的捆绑文件获得不同的结果以获得以下结果。

var file2 = { value: 'bling bling' }; console.log('this is the file 2 object value', file2.value);

我只是希望我的代码在最终结果中没有任何额外的 browserify 或 webpack 或 requirejs 编码,可能是我只是错误地使用了该工具,但我在使用这些工具时总是会发生这种情况。

其中一些工具会产生或多或少的编码,但我不知道如何删除这些额外的代码。

可以使用rollup,默认使用es6模块。 Es6 导入是静态的,所以你的 bundle 将没有 require 函数或任何东西。您的代码将是:
文件 1

export default {
    value: 'bling bling'
};

文件 2

import file2 from './file2.js';

console.log('this is the file 2 object value', file2.value);

在我的项目中,我运行使用以下命令来使用汇总:

./node_modules/rollup/bin/rollup file1.js

这是关于 es6 模块的more information