webpack中的externals应该怎么理解?

externals: {
    lodash: {
        commonjs: 'lodash',
        commonjs2: 'lodash',
        amd: 'lodash',
        root: '_'
    }
}

Externalize Lodash

Now, if you run webpack, you will find that a largish bundle is created. If you inspect the file, you'll see that lodash has been bundled along with your code. In this case, we'd prefer to treat lodash as a peerDependency. Meaning that the consumer should already have lodash installed. Hence you would want to give up control of this external library to the consumer of your library.

This can be done using the externals configuration:

webpack.config.js

  var path = require('path');

  module.exports = {
    entry: './src/index.js',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'webpack-numbers.js'
-   }
+   },
+   externals: {
+     lodash: {
+       commonjs: 'lodash',
+       commonjs2: 'lodash',
+       amd: 'lodash',
+       root: '_'
+     }
+   }
  };

This means that your library expects a dependency named lodash to be available in the consumer's environment.

T> Note that if you only plan on using your library as a dependency in another webpack bundle, you may specify externals as an array.

External Limitations

For libraries that use several files from a dependency:

import A from 'library/one';
import B from 'library/two';

// ...

You won't be able to exclude them from bundle by specifying library in the externals. You'll either need to exclude them one by one or by using a regular expression.

externals: [
  'library/one',
  'library/two',
  // Everything that starts with "library/"
  /^library\/.+$/
]

对比 Node.js 模块,webpack 模块能够以各种方式表达它们的依赖关系,几个例子如下

ES2015 import 语句

CommonJS require() 语句

AMD definerequire 语句

支持的模块类型

webpack 通过 loader 可以支持各种语言和预处理器编写模块。loader 描述了 webpack 如何处理 非 JavaScript(non-JavaScript) 模块,并且在bundle中引入这些依赖。 webpack 社区已经为各种流行语言和语言处理器构建了 loader,包括

  • CoffeeScript
  • TypeScript
  • ESNext (Babel)
  • Sass
  • Less
  • Stylus

总的来说,webpack 提供了可定制的、强大和丰富的 API,允许任何技术栈使用 webpack,保持了在你的开发、测试和生成流程中无侵入性(non-opinionated)。

module: {
 rules: [
   {
     test: /\.css$/,
     use: [
       'style-loader',
       'css-loader'
     ]
   }
 ]
}

Meaning that the consumer should already have lodash installed. Hence you would want to give up control of this external library to the consumer of your library.

意思是消费者应该已经安装了lodash。 因此,你将想要放弃额外的第三方库的控制,对你的第三方库的消费者

This means that your library expects a dependency named lodash to be available in the consumer's environment.

这意味着你的第三方库要求一个名为lodash的依赖,在消费者的环境中可用。

阅读 4.1k
2 个回答
externals: {
    lodash: {
        commonjs: 'lodash',
        commonjs2: 'lodash',
        amd: 'lodash',
        root: '_'
    }
}

这里 lodash 这个外部 library 可以在 AMD 和 CommonJS 模块系统中通过 lodash 访问,但在全局变量形式下用 _ 访问。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题