报错如下图所示

根据这个报错的内容可知 应该是CSS文件的问题,因此我依次进行了以下检查:

1.在js文件中导入css的文件路径是否正确 正确

2.是否安装相应的loader插件对CSS文件进行处理  也安装好了

3.文件结构检查,确保css文件夹处于src文件下面,形成如下结构

project/
├── src/
│   ├── css/
│   │   └── index.css
│   ├── index.html
│   └── index1.js
├── package.json
└── webpack.config.js

最终我去检查了我的webpack.config.js文件,发现是这个地方出了问题,我的webpack.config.js内容如下:

const path = require('path')
//1.导入HTML插件,得到一个构造函数
const HtmlPlugin = require('html-webpack-plugin')
const { Template } = require('webpack')
//2.创建HTML插件的实例对象
const htmlPlugin = new HtmlPlugin({
    template: './src/index.html',  //指定原文件的存放路径
    filename: './index.html'    //指定生成的文件的存放路径
})
//使用node.js中的语法向外到处一个webpack配置项 
module.exports = {
    mode: 'development', // 设置mode   development为开发环境,production为生产环境
    //指定要处理的文件,而不是默认文件
    entry: path.join(__dirname,'./src/index1.js'),
    output: {
    //存放到目录
    path: path.join(__dirname,'dist'),
    //生成的文件名
    filename: 'bundle.js'
    },
    plugins: [htmlPlugin], //3.通过plugins节点,使htmlPlugin插件生效
    devServer:{
        open: true,
        port: 8081,
        host: '127.0.0.1'
    }
}
module: { //所有第三方文件模块的匹配规则
    rules: [//文件后缀名的匹配规则
        {
            test: /\.css$/,
            use: ['style-loader','css-loader']
        }

    ]
}

因为是初学者,并未关注到Module这个模块的放置问题,只是在下面就展开了书写,VS也并未报出语法错误,但正确的是其应该在module.exports中书写。正确代码如下所示:

const path = require('path');
// 1. 导入HTML插件
const HtmlPlugin = require('html-webpack-plugin');

// 2. 创建HTML插件的实例对象
const htmlPlugin = new HtmlPlugin({
  template: './src/index.html',  // 指定原文件的存放路径
  filename: './index.html'      // 指定生成的文件的存放路径
});

// 使用node.js导出webpack配置项 
module.exports = {
  mode: 'development', // development为开发环境,production为生产环境
  entry: path.join(__dirname, './src/index1.js'),
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [htmlPlugin], // 3. 通过plugins节点使插件生效
  devServer: {
    open: true,
    port: 8081,
    host: '127.0.0.1'
  },
  // 所有第三方文件模块的匹配规则
  module: {
    rules: [
      // 文件后缀名的匹配规则
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};

希望此文可以帮助到和我遇到同样问题的小伙伴!

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐