Skip to content

前端项目优化

HTML

CSS

JavaScript

构建优化

移除console

npm install babel-plugin-transform-remove-console --D

js
// babel.config.js
const proPlugins = []
if (process.env.NODE_ENV === 'production')
  proPlugins.push('transform-remove-console')

module.exports = {
  plugins: [
    ...proPlugins
  ]
}

分包和共享依赖

js
// webpack.config.js
module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve('src'),
      },
    },
    optimization: {
      runtimeChunk: 'single',
      splitChunks: {
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 20000,
        cacheGroups: {
          common: {
            name: 'common',
            chunks: 'all',
            minSize: 0, // 只要大于0字节就抽离
            minChunks: 2,
          },
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            chunks: 'initial', // 从入口文件抽离
            minSize: 0, // 只要大于0字节就抽离
            minChunks: 2, // 只要使用2次以上就抽离
            name(module) {
              const packageName = module.context.match(
                /[\\/]node_modules[\\/](.*?)([\\/]|$)/
              )[1]
              return `npm.${packageName.replace('@', '')}`
            },
          },
        },
      },
    },
  }
}