我正在尝试将基于 requireJS 的应用程序迁移到 webpack。
这个应用程序没有很多依赖项 - 实际上它只需要一个承诺的 polyfill - 我已经想出了如何使用缩小的 webpack 制作 webpack。
requireJS 的捆绑包大小曾经是 43KB,使用 webpack 时是 121KB。
虽然 121KB 并不是很大,但这是一个显着的大小增加。
通过运行webpack --display-reasons --display-modules
我了解到我的捆绑包中似乎包含一些node_module依赖项。比我预期的要多。
我看到像buffer
、readable-stream
、stream-http
、stream-browserify
、core-util-is
、buffer-shims
、...
这是预期的/webpack包装器代码的一部分吗?
我可以做些什么来排除这些依赖项?
这是我的webpack.config.js:
var webpack = require('webpack');
module.exports = {
entry: {
"mynexuz": "./js/mynexuz-api.js",
"kws": "./js/kws-api.js",
"main": "./js/main.js",
"quest": "./js/quest.js"
},
output: {
filename: "./dist/[name]-bundle.js",
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
}
})
],
node: {
//stream: false,
//process: false,
//global: false
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
modules: ['js', 'js/lib', 'node_modules'],
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
module: {
loaders: [
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
test: /.js$/,
loader: "source-map-loader",
exclude: /node_modules/
},
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{
test: /.tsx?$/,
loader: "awesome-typescript-loader",
exclude: /node_modules/
}
]
},
};
这不适用于您正在使用的所有库,但如果可能的话,您可以通过仅导入您需要使用的实际函数/组件来节省文件大小。
这是 lodash 的示例
import has from 'lodash/has';
上面的方式只会导入has
方法。
但是,如果您执行以下任一操作:
import { has } from 'lodash';
或
import _ from 'lodash';
然后,您将导入所有 lodash 库,这将增加您的文件大小。
但是,对于其他库(即当前版本的 moment.js(,仅导入所需库的一部分并不那么简单。
还有其他几种方法可以尝试解决此问题(即调整您的 webpack 设置(,但我会从这种方法开始。
在深入研究了这个问题之后,我找到了捆绑包尺寸过大的原因。在真正的requireJS风格中,我有:
define(['http', 'config'], function (Http, Config) { ... });
这个"http"的东西应该指的是我自己的库,但 webpack 将其解析为某个 NPM 模块,引入了所有上述依赖项。
我现在已将代码更改为:
define(['./http', 'config'], function (Http, Config) { ... });
捆绑包大小回到44KB左右。