Rule.resource作用说明
1. 说明
作用
Rule.resource 用于定义哪些文件需要被当前规则处理。它是对传统 test、include、exclude 的更底层封装,支持更灵活的匹配方式。
与 test/include/exclude 的关系
test: /.js$/ 等价于resource: { test: /.js$/ }
include: path.resolve(__dirname, ‘src’) 等价于 resource: { include: path… }
exclude: /node_modules/ 等价于 resource: { exclude: /node_modules/ }
因此,Rule.resource 可以替代 test/include/exclude,实现更复杂的组合条件
配置代码
- webpack.config.js
const path = require('path');
module.exports = {entry: "./src/index.js",output: {path: path.resolve(__dirname, 'dist1'),publicPath: "/dist1/"},module: {rules: [{resource: {test: /\.js$/, // 匹配 .js 文件include: path.resolve(__dirname, 'src/js'), // 仅处理 src 目录下的文件exclude: /node_modules/, // 排除 node_modules},use: ['babel-loader'], // 应用 Babel 转译},],},optimization: {minimize: false}
}
- index.js
import a from './a.js'
import aa from './js/aa.js'a()
aa()
- a.js
const a = () => {console.log('this is a')
}export default a
- js/aa.js
const aa = () => {console.log('this is an anarow faunction')
}
export default aa
- .babelrc
{"presets": ["@babel/preset-env"]
}
在上述代码中,分别在两个文件里使用了箭头函数,然后在打包配置里只设置了会对 src/js 这个目录下的js进行代码打包编译