webpack打包提示: Uncaught Error: Cannot find module 'strip-ansi'

发布于 2022-09-12 01:40:54 字数 8804 浏览 26 评论 0

运行webpack-dev-server的时候,可以正常启动服务,但是Terminal控制台报错,如下:

ERROR in (webpack)-dev-server/client?http://localhost:8080
Module not found: Error: Can't resolve './overlay' in 'F:\webpack\node_modules\webpack-dev-server\client'
 @ (webpack)-dev-server/client?http://localhost:8080 10:14-34
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

ERROR in (webpack)-dev-server/client?http://localhost:8080
Module not found: Error: Can't resolve './socket' in 'F:\webpack\node_modules\webpack-dev-server\client'
 @ (webpack)-dev-server/client?http://localhost:8080 8:13-32
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

ERROR in (webpack)-dev-server/client?http://localhost:8080
Module not found: Error: Can't resolve './utils/createSocketUrl' in 'F:\webpack\node_modules\webpack-dev-server\client'
 @ (webpack)-dev-server/client?http://localhost:8080 20:22-56
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

ERROR in (webpack)-dev-server/client?http://localhost:8080
Module not found: Error: Can't resolve './utils/log' in 'F:\webpack\node_modules\webpack-dev-server\client'
 @ (webpack)-dev-server/client?http://localhost:8080 12:15-37
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

ERROR in (webpack)-dev-server/client?http://localhost:8080
Module not found: Error: Can't resolve './utils/reloadApp' in 'F:\webpack\node_modules\webpack-dev-server\client'
 @ (webpack)-dev-server/client?http://localhost:8080 18:16-44
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

ERROR in (webpack)-dev-server/client?http://localhost:8080
Module not found: Error: Can't resolve './utils/sendMessage' in 'F:\webpack\node_modules\webpack-dev-server\client'
 @ (webpack)-dev-server/client?http://localhost:8080 16:18-48
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

ERROR in (webpack)-dev-server/client?http://localhost:8080
Module not found: Error: Can't resolve 'strip-ansi' in 'F:\webpack\node_modules\webpack-dev-server\client'
 @ (webpack)-dev-server/client?http://localhost:8080 6:16-37
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js

同时,chrome的控制台也抛出了错误

Uncaught Error: Cannot find module 'strip-ansi'
    at webpackMissingModule (client:6)
    at Object.<anonymous> (client:6)
    at Object../node_modules/webpack-dev-server/client/index.js?http://localhost:8080 (bundle.js:274)
    at __webpack_require__ (bootstrap:19)
    at Object.0 (bundle.js:365)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83

webpack.config.js配置

const path = require('path');
const Webpack = require('webpack');
const HtmlWebpackPlaugin = require('html-webpack-plugin');  // 把打包后的文件直接注入到html模板中
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // 提取css到单独文件
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); // 压缩css
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // 压缩js
const { CleanWebpackPlugin } = require('clean-webpack-plugin'); // 每次运行前清理目录
const CopyWebpackPlugin = require('copy-webpack-plugin'); // 拷贝文件

module.exports = {
  mode: 'development', // 默认production生产模式  development开发模式
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    // publicPath: 'www.hyfm.com'
  },
  devtool: 'source-map',
  watch: true, // 实时监控打包
  watchOptions: {
    poll: 1000, //监控间隔
    aggregateTimeout: 500, // 间隔毫秒 (防抖)
    ignored: /node_modules/, // 不要监控的文件
  },
  // 开发服务器的配置
  devServer: {
    // port: 8090,
    progress: true, // 打包进度条
    // open: true, // 自动打开浏览器
    contentBase: './dist', // 指定静态目录文件夹
    compress: true, // gzip压缩,
    proxy: {
      // 配置代理,并重新路径
      // 'api': {
      //   target: 'http://www.hyfm.com/v1/api',
      //   pathRewirte:{
      //     '/api': '',
      //   }
      // },

      // // 模拟交互
      // before(app) {
      //   app.get('/data', (req, res) => {
      //     res.json({
      //       status: 200,
      //       data: [1, 2, 3, 4, 5],
      //     })
      //   })
      // }
      before: function(app, server, compiler) {
        app.get('/some', function(req, res) {
          res.json({ custom: 'response' });
        });
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: {
          loader: 'html-withimg-loader',
        },
        exclude: /node_modules/,
      },
      {
        test: /\.(png|jpg|jpeg|gif|bpm)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 60*1024, // 小于60k的图片会被打包成base64
            esModule: false, // 图片路径避免出现default
            outputPath: '/img',
            publicPath: '',
          }
        },
      },
      {
        test: /\.js$/,
        use: {
          loader: 'eslint-loader',
          options: {
            enforce: 'pre', // pre前置 normarl正常 post后置
          }
        },
        exclude: /node_modules/,
      },
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env'
            ],
            plugins: [
              ["@babel/plugin-proposal-decorators", { "legacy": true }],
              ["@babel/plugin-proposal-class-properties", { "loose" : true }],
              '@babel/plugin-transform-runtime'
            ]
          }
        },
        exclude: /node_modules/,
        // include: './src'
      },
      { test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader']
      },
      {
        test: /\.less$/,
        use: [
          // {
          //   loader: 'style-loader',
          //   options: {
          //     insert: 'top', // body || id || tag
          //   }
          // },
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'less-loader'
        ]
      }
    ]
  },

  // 路径解析
  resolve: {
    modules: [path.resolve('node_modules')],
    // mainFields: ['main', 'style'], // 文件解析的顺序【package.json】
    // mainFiles: ['index.js'], // 入口文件
    extensions: ['js', 'json', 'less', 'css'], // 导入文件的扩展名称顺序
    alias: {
      components: './src/components'
    }
  },
  // 插件
  plugins: [
    // new Webpack.DefinePlugin({
    //   DEV: JSON.stringify('this is dev'),
    // }),

    // 处理Html
    new HtmlWebpackPlaugin({
      template: "./index.html", // 模板文件路径
      filename: 'index.html', // 打包后的文件名称
      minify: {
        caseSensitive: true, // 是否对大小写敏感,默认false

        collapseBooleanAttributes: true, // 是否简写boolean格式的属性如:disabled="disabled" 简写为disabled  默认false

        collapseWhitespace: true, // 是否去除空格,默认false

        minifyCSS: true, // 是否压缩html里的css(使用clean-css进行的压缩) 默认值false;

        minifyJS: true, // 是否压缩html里的js(使用uglify-js进行的压缩)

        preventAttributesEscaping: true, // Prevents the escaping of the values of attributes

        removeAttributeQuotes: true, // 是否移除属性的引号 默认false

        removeComments: true, // 是否移除注释 默认false

        removeCommentsFromCDATA: true, // 从脚本和样式删除的注释 默认false

        removeEmptyAttributes: true, // 是否删除空属性,默认false

        removeOptionalTags: false, // 若开启此项,生成的html中没有 body 和 head,html也未闭合

        removeRedundantAttributes: true, // 删除多余的属性

        removeScriptTypeAttributes: true, // 删除script的类型属性,在h5下面script的type默认值:text/javascript 默认值false

        removeStyleLinkTypeAttributes: true, // 删除style的类型属性, type="text/css" 同上

        useShortDoctype: true, // 使用短的文档类型,默认false
      }
    }),
    new MiniCssExtractPlugin({
      filename: '/css/[name].css',
      chunkFilename: '/css/[id].css',
    }),

    // 拷贝静态文件
    new CopyWebpackPlugin(
      [
        { from: './static', to: 'static' },
      ]
    ),

    // 清空文件
    new CleanWebpackPlugin(),

    new Webpack.BannerPlugin('link1024'),
  ],

  // 优化项
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        sourceMap: false, // 源码映射
        parallel: true, // 使用多进程并行运行来提高构建速度
        cache: true, // 是否启用文件缓存,默认缓存在node_modules/.cache/uglifyjs-webpack-plugin.目录
      }),
      new OptimizeCssAssetsPlugin(),
    ]
  }
};

尝试过的方法【无效】

1.重新安装 strip-ansi

yarn add strip-ansi -D

2.删除node_modules目录,重新安装依赖

rm -rf node_modules
yarn install

3.重新安装本地webpack

yarn add webpack -D

以上3种方法均未解决问题

解决问题

仔细排查了一下发现,extensions配置扩展名称的时候,少了一个点(.)

  resolve: {
    extensions: ['.js', '.json', '.less', '.css'],
  },

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

合久必婚 2022-09-19 01:40:54

仔细排查了一下发现,extensions配置扩展名称的时候,少了一个点(.)

  resolve: {
    extensions: ['.js', '.json', '.less', '.css'],
  },
隱形的亼 2022-09-19 01:40:54

谢谢大哥!!!我遇到问题和你一模一样哈哈哈哈哈

鸢与 2022-09-19 01:40:54

哈哈裂开,我也遇到了 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文