prueba de humo webpack4

1、下载
	cnpm install -D rimraf
	cnpm install -D mocha

2、引入配置好的webpack环境,通过rimraf库每次运行删除dist目录,通过mocha添加测试脚本
	(1)配置mocha
		const mocha = new Mocha({
		  timeout: 10000,
		})
	(2)每次运行删除dist目录,并在其中通过webpack方法运行webpack配置等
		rimraf('./dist',()=>{
			webpack(prodConfig, (err,stats) => {
				if(err){
					process.exit(2);
				}
				成功打印构建结果
				console.log(stats.toString({ 指定显示内容
					  colors: true,			
 					  modules: false,
				      children: false
				}))
				使用mocha添加测试脚本
				 mocha.addFile(path.join(__dirname, 'html-test.js'))
				 mocha.addFile(path.join(__dirname, 'css-js-test.js'))
				 mocha.run();

			})
		})
		
3、编写mocha测试脚本检验是否打包生成对应文件
	const glob = require('glob');
	
	describe('checking xx', () => {
		it('测试描述', (done) => {
			通过glob库匹配文件是否生成
			如果成功执行done()
			如果失败throw new Error('xxx')
		}
 	})

La prueba pasó el resultado:
Inserte la descripción de la imagen aquí

Ejemplo de código:
archivo de entrada de prueba

const path = require('path');
const webpack = require('webpack');
const rimraf = require('rimraf');
const Mocha = require('mocha');

const mocha = new Mocha({
    
    
  timeout: 10000,
})

//修改进程的运行目录为如下,即其他地方通过process.cwd()获取到的目录都为指定目录
process.chdir(path.join(__dirname, 'template'));

rimraf('./dist', () => {
    
    
  const prodConfig = require('../../lib/webpack.prod');

  webpack(prodConfig, (err,stats) => {
    
    
    if (err) {
    
    
      console.log(err);
      process.exit(2);
    }

    //打印构建结果
    console.log(stats.toString({
    
    
      colors: true,
      modules: false,
      children: false
    }));

    console.log('开始测试')
    mocha.addFile(path.join(__dirname, 'html-test.js'))
    mocha.addFile(path.join(__dirname, 'css-js-test.js'))

    mocha.run();
  })
})

Secuencia de comandos de prueba

const glob = require('glob');

describe('checking html', () => {
    
    
  it('should generate html files', (done) => {
    
    
    const files = glob.sync(process.cwd()+'/dist/*.html')
    
    if (files.length > 0) {
    
    
      done();
    } else {
    
    
      throw new Error('no html files')
    }
  })
})

webpack.base.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {
    
     CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const glob = require('glob');

const projectPath = process.cwd();


const setOptions = () => {
    
    
  const entry = {
    
    };
  const htmlWebpackPlugin = [];

  const entryFiles = glob.sync(path.resolve(projectPath, './src/*/index.js'));
  const fileReg = /src\/(.*)\/index\.js/;

  entryFiles.forEach((filePath) => {
    
    
    const fileName = filePath.match(fileReg);

    entry[fileName[1]] = filePath;
    htmlWebpackPlugin.push(
      new HtmlWebpackPlugin({
    
    
        template: path.join(projectPath,`./src/${
      
      fileName[1]}/index.html`),
        filename: `${
    
    fileName[1]}.html`,
        chunks: [fileName[1]],
      }),
    );
  });

  return {
    
    
    entry,
    htmlWebpackPlugin,
  };
};

module.exports = {
    
    
  entry: setOptions().entry,
  output: {
    
    
    path: path.resolve(projectPath, 'dist'),
    filename: '[name]_[chunkhash:8].js',
  },
  module: {
    
    
    rules: [
      {
    
    
        test: /\.js$/,
        use: ['babel-loader'],
      },
      {
    
    
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
    
    
            loader: 'postcss-loader',
            options: {
    
    
              postcssOptions: {
    
    
                plugins: [
                  [
                    'autoprefixer',
                    {
    
    
                      overrideBrowserslist: [
                        'Android 4.1',
                        'iOS 7.1',
                        'Chrome > 31',
                        'ff > 31',
                        'ie >= 8',
                        '> 1%', // 必须大于 1% 用户使用的浏览器
                        // 'last 2 versions', // 所有主流浏览器最近的 2个版本
                      ],
                    },
                  ],
                ],
              },
            },
          },
          {
    
    
            loader: 'px2rem-loader',
            options: {
    
    
              remUnit: 75, // 初始稿的10分之一,代表设计稿为750,1rem=75px,
              remPrecision: 8, // 精确的小数点位数
            },
          },
        ],
      },
      {
    
    
        test: /\.txt$/i,
        use: [
          {
    
    
            loader: 'raw-loader',
            options: {
    
    
              esModule: false,
            },
          },
        ],
      },
    ],
  },
  mode: 'development',
  plugins: [
    ...setOptions().htmlWebpackPlugin,
    new MiniCssExtractPlugin({
    
     filename: 'css/build.css' }),
    new CleanWebpackPlugin(),
    new FriendlyErrorsWebpackPlugin(),
    function errorPlugin() {
    
    
      this.hooks.done.tap('done', (stats) => {
    
    
        if (stats.compilation.errors && stats.compilation.errors.length && process.argv.indexOf('--watch') === -1) {
    
    
          // eslint-disable-next-line
          console.log('build error');
          process.exit(1);
        }
      });
    },
  ],
};

webpack.prod.js:

const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin');
const {
    
     merge } = require('webpack-merge');
const baseConfig = require('./webpack.base');

const prodConfig = {
    
    
  mode: 'production',
  optimization: {
    
    
    splitChunks: {
    
    
      minSize: 0,
      cacheGroups: {
    
    
        commons: {
    
    
          minChunks: 2,
          chunks: 'all',
          name: 'commons',

        },
      },
    },
  },
  plugins: [
    new OptimizeCssAssetsPlugin(),
    new HtmlWebpackExternalsPlugin({
    
    
      externals: [
        {
    
    
          module: 'react',
          entry: 'https://11.url.cn/now/lib/16.2.0/react.min.js',
          global: 'React',
        },
        {
    
    
          module: 'react-dom',
          entry: 'https://11.url.cn/now/lib/16.2.0/react-dom.min.js',
          global: 'React-dom',
        },
      ],
    }),
  ],
};

module.exports = merge(baseConfig, prodConfig);

webpack.dev.js:

const {
    
     merge } = require('webpack-merge');
const baseConfig = require('./webpack.base');

const devConfig = {
    
    
  mode: 'development',
  devServer: {
    
    
    contentBase: './dist',
    hot: true,
    open: true,
    // stats:'errors-only'
  },
  devtool: 'cheap-source-map',
};

module.exports = merge(baseConfig, devConfig);

Supongo que te gusta

Origin blog.csdn.net/weixin_43294560/article/details/113479175
Recomendado
Clasificación