在写webpack配置时,经常会有某些通用配置,比如

  • 入口、出口配置
  • 文件拷贝配置
  • vue配置
  • react配置
  • 样式配置,less、css module…
  • 压缩配置

我们可以抽离将这些常见的配置出来,然后通过 webpack-merge 组装成1个完整的配置。

1 抽离

示例:抽离出的配置,移步到这里查看,

image.png

1.1 示例-react配置

  1. /**
  2. * react jsx 处理配置
  3. */
  4. module.exports = function() {
  5. return {
  6. module: {
  7. rules: [
  8. {
  9. resource: {
  10. test: /\.jsx$/,
  11. // exclude: [/(node_modules|bower_components)/, /\.test\.js$/],
  12. },
  13. use: {
  14. loader: 'babel-loader',
  15. options: {
  16. cacheDirectory: true,
  17. presets: [require.resolve('smash-helper-babel-preset-react')],
  18. },
  19. },
  20. },
  21. ],
  22. },
  23. };
  24. };

1.2 vue配置示例

  1. const VueLoaderPlugin = require('vue-loader/lib/plugin');
  2. module.exports = function() {
  3. return {
  4. plugins: [new VueLoaderPlugin()],
  5. module: {
  6. rules: [
  7. {
  8. test: /\.vue$/,
  9. use: ['vue-loader'],
  10. },
  11. ],
  12. },
  13. };
  14. };

2 组装

  1. const megre = require('webpack-merge');
  2. const _common = require('./cell/webpack.common');
  3. const _html = require('./cell/webpack.html');
  4. const _style = require('./cell/webpack.style');
  5. const _js = require('./cell/webpack.js.js');
  6. const _json = require('./cell/webpack.json.js');
  7. const _reactJSX = require('./cell/webpack.react.jsx.js');
  8. const _vue = require('./cell/webpack.vue.js');
  9. const _jsHtmlEntry = require('./cell/webpack.jsHtmlEntry'); // js入口、html模板入口
  10. const _minify = require('./cell/webpack.minify');
  11. module.exports = function(isProd = true) {
  12. return megre(_common(), _html(), _style(isProd), _js(), _json(), _reactJSX(), _vue(), _jsHtmlEntry(), _minify(), {
  13. // 设为开发模式,可显著提升构建速度
  14. mode: 'development',
  15. // 开发模式下使用这个模式,可在浏览器开发者工具阅读原始源代码,并且重新构建速度较快
  16. devtool: 'eval-source-map',
  17. // watch 和 watchOptions
  18. // https://webpack.docschina.org/configuration/watch/
  19. watch: true,
  20. watchOptions: {
  21. ignored: /node_modules/,
  22. },
  23. });
  24. };