Out of the box, webpack only understands JavaScript files. Loaders allow webpack to process other types of files and converting them into valid modules that can be consumed by your application and added to the dependency graph.、
module: { rules: [ { test: /\.css$/, use: [ { loader: ‘style-loader‘ }, { loader: ‘css-loader‘, options: { modules: true } } ] } ] }
import Styles from ‘style-loader!css-loader?modules!./styles.css‘;
webpack --module-bind jade-loader --module-bind ‘css=style-loader!css-loader‘
//src/loader.js const {getOptions} = require(‘loader-utils‘) module.exports = function (source){ const options = getOptions(this); console.log(source); source = source.replace(/\[name\]/g, options.name); console.log(source); return `export default ${JSON.stringify(source)}` }
//webpack.config.js配置 const path = require(‘path‘) module.exports = { mode:‘development‘, context: __dirname, entry: `./src/test.txt`, output: { path: path.resolve(__dirname, ‘dist‘), filename: ‘bundle.txt‘ }, module: { rules: [ { test: /\.txt$/, use: [ { loader: path.resolve(__dirname, ‘./src/bar-loader.js‘), options: { name: ‘18hahaha‘ } }, { loader: path.resolve(__dirname, ‘./src/loader.js‘), options: { name: ‘17‘ } } ] } ] } }
那么如何编写一个loader与现有的loader一起使用呢?
//src/bar-loader.js const { getOptions } = require(‘loader-utils‘) module.exports = function (source) { const options = getOptions(this); console.log(11111,source); source = source.replace(/17/g, options.name); console.log(11111, source); return `export default ${JSON.stringify(source)}` }
//webpack.config.js rules: [ { test: /\.txt$/, use: [ { loader: path.resolve(__dirname, ‘./src/bar-loader.js‘), options: { name: ‘18hahaha‘ } }, { loader: path.resolve(__dirname, ‘./src/loader.js‘), options: { name: ‘17‘ } } ] } ]
module.exports = function(content) { var callback = this.async(); if(!callback) return someSyncOperation(content); someAsyncOperation(content, function(err, result) { if(err) return callback(err); callback(null, result); }); };
import path from ‘path‘ import webpack from ‘webpack‘ import memoryfs from ‘memory-fs‘ export default (fixture, options = {}) => { const compiler = webpack({ context: __dirname, entry: `./${fixture}`, output: { path: path.resolve(__dirname), filename: ‘bundle.js‘ }, module:{ rules:[ { test: /\.txt$/, use: { loader: path.resolve(__dirname, ‘../loaders/loader.js‘), options: { name: ‘17‘ } } } ] } }) compiler.outputFileSystem = new memoryfs(); return new Promise((resolve, reject) => { compiler.run((err, stats) => { if(err) reject(err) resolve(stats) }) }) }
import compiler from ‘./compiler.js‘; test(‘Inserts name and outputs JavaScript‘, async () => { const stats = await compiler(‘example.txt‘); // console.log(stats.toJson()); const output = stats.toJson().modules[0].source; expect(output).toBe(`export default "Hey 17!\\n"`); });
原文:https://www.cnblogs.com/yiyi17/p/12161617.html