babel-loader
2024年04月06日
一、认识
babel-loader
逻辑为通过 @babel/core
以及对应的配置将我们的js
文件进行转化
二、实现
const core = require('@babel/core');
function babelLoader(sourceCode, sourceMap, meta) {
// 获取loader参数
const options = this.getOptions() || {};
// 生成 babel 转译阶段的 sourcemap
options.sourceMaps = true;
// 保存之前 loader 传递进入的 sourceMap
options.inputSourceMap = sourceMap;
// 获取处理的资源文件名
options.filename = this.request.split('!').pop().split('/').pop();
// 调用 babel 的转换方法
const { code, map, ast } = core.transform(sourceCode, options);
// 调用 this.callback 表示 loader 执行完毕, 同时传递多个参数给下一个 loader
this.callback(null, code, map, ast);
}
module.exports = babelLoader;
三、测试
3.1 test/webpack/bolawen01/loaders/babel-loader/example/webpack.config.js
const Path = require('path');
module.exports = {
entry: Path.resolve(__dirname, './index.js'),
mode: 'development',
output: {
filename: '[name].js',
path: Path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
loader: Path.resolve(__dirname, '../core/index.js'),
options: {
presets: [['@babel/preset-env', { targets: { chrome: '67' } }]]
}
}
]
}
};