You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Webpack打包压缩JS/CSS时遇Module not found错误求助

Webpack打包时Module not found错误的解决办法

问题概况

要将src/js下所有JS打包为assets/scripts.bundle.min.js,src/css下所有CSS打包为assets/styles.bundle.min.css,目录结构如下:

root
|- assets
|- src
|-- js
|--- *.js
|-- css
|--- *.css

执行npx webpack --config webpack.config.js时,所有JS/CSS文件均报错:

ERROR in [...]
Module not found: Error: Can't resolve 'src\css[...].css' in '[...]'
Did you mean './src\css[...].css'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.

可行解决步骤

1. 修正入口路径的解析格式

问题核心是Webpack把不带./的路径当成npm模块去node_modules查找,而非本地文件。可以通过path.resolve将glob匹配到的路径转为绝对路径,确保Webpack能正确识别:

entry: {
    scripts: glob.sync('./src/js/*.js').map(file => path.resolve(__dirname, file)),
    styles: glob.sync('./src/css/*.css').map(file => path.resolve(__dirname, file))
}

或统一转换路径分隔符(适配Windows环境):

entry: {
    scripts: glob.sync('./src/js/*.js').map(file => file.replace(/\\/g, '/')),
    styles: glob.sync('./src/css/*.css').map(file => file.replace(/\\/g, '/'))
}

2. 启用resolve.preferRelative配置

直接按错误提示添加resolve.preferRelative: true,让Webpack优先在当前目录解析以目录名开头的请求:

module.exports = {
    // ...其他原有配置
    resolve: {
        preferRelative: true
    },
    // ...其他原有配置
}

3. 改用JS入口引入CSS(更规范的方式)

Webpack本质是模块打包工具,更推荐创建一个JS文件来统一引入所有CSS,而非直接把CSS作为入口:

  1. 在src/css下新建index.js,内容为:
// 引入所有CSS文件,示例:
import './style1.css';
import './style2.css';
  1. 修改entry配置:
entry: {
    scripts: glob.sync('./src/js/*.js'),
    styles: './src/css/index.js'
}

这种方式能避免直接处理CSS入口带来的路径解析异常。

4. 验证glob匹配结果

在配置文件中添加打印语句,确认glob是否匹配到正确的文件路径:

const jsFiles = glob.sync('./src/js/*.js');
console.log('匹配到的JS文件:', jsFiles);
const cssFiles = glob.sync('./src/css/*.css');
console.log('匹配到的CSS文件:', cssFiles);

module.exports = {
    // ...原有配置
}

执行Webpack命令时查看控制台输出,如果路径不带./,手动补充:

scripts: jsFiles.map(file => `./${file}`),
styles: cssFiles.map(file => `./${file}`)

内容的提问来源于stack exchange,提问作者thelos999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 13:00:25