0

如何使用 browserify 或 webpack 正确填充 javascript 而无需额外文件?

让我们以使用 react 或 react-redux 为例。我在 package.json 中有这个配置:

{
  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": [
            "es2015",
            "react"
          ]
        }
      ],
      "browserify-shim"
    ]
  },
  "browserify-shim": {
    "jquery": "global:$",
    "react": "global:React",
    "react-addons-update": "global:React.addons.update",
    "react-dom": "global:ReactDOM",
  },
  "dependencies": {
    "react": "^0.14.3",
    "react-addons-update": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-redux": "^4.4.0",
    "redux": "^3.3.1",
    "redux-logger": "^2.6.0",
    "redux-thunk": "^1.0.3",
  },
  "devDependencies": {
    "uglify-js": "~2.5.0",
    "babel-cli": "^6.1.1",
    "babel-eslint": "^5.0.0",
    "babel-polyfill": "^6.5.0",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-react": "^6.0.15",
    "babelify": "^7.2.0",
    "browserify": "^13.0.0",
    "browserify-shim": "~3.8.12",
    "clean-css": "~3.4.6",
    "eslint": "^2.2.0",
    "eslint-plugin-react": "^4.1.0",
  }
}

在我的项目中,我将 react-redux 与 line 一起使用import { createStore, applyMiddleware } from 'redux';,并添加了 react-redux 作为依赖项。当我编译我的项目时,它会生成一个大约 20K 行的 javascript 文件。

问题是,当我填充 react-redux 时,通过使用 react-redux 的 cdnjs ( https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.0/react-redux.js) 并将其添加到 browserify-shim 配置中,我的项目仅使用大约 2K 行,而仅 react-redux js 文件仅使用大约 700 行(该项目仍然有效!)。

为什么会发生?我可以不在 browserify-shim 中添加 react-redux 但仍然只在我编译的项目 javascript 中添加 700 行而不是 18K 行吗?

这里实际发生了什么魔法,魔法实际上是如何起作用的?

4

1 回答 1

0

当您通过 CDN 使用 react-redux 时"global:react-redux",browserify-shim 只是要求 js 包通过window. 例如,在一个测试中,我运行我的 browserified 包只有 8 行。第一个是browserify-shim 样板文件,最后七个完全按照我上面的描述:

(function (global){
(typeof window !== "undefined" ? window['$'] : typeof global !== "undefined" ? global['$'] : null);
(typeof window !== "undefined" ? window['react-redux'] : typeof global !== "undefined" ? global['react-redux'] : null);
(typeof window !== "undefined" ? window['react'] : typeof global !== "undefined" ? global['react'] : null);

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 
},{}]},{},[1]);

当您将包实际捆绑到浏览器化的捆绑包中时(意味着它们不是通过 CDN 加载的),捆绑包必须包含所有源代码。我用相同的包再次尝试了这个:jQuery、React 和 React-redux,而不是我的包中的七行,我得到了超过 30,000 行。这是有道理的,因为整个 jQuery、React、React-redux 包都包含在该包中。

如果没有看到您的完整package.json和输出文件,就很难说更多。希望能帮助到你!

于 2016-03-08T14:55:39.720 回答