首先亮出webpack官方网站,webpack能干什么?官网给出的答案就是,一句话,让一切变得简单!
各式各样的loader层出不穷,让我们在构建时不知所措,于此,总结下loader的全解析。
概念
loader,顾名思义,加载器,英文的解释如下:
Loaders are transformations that are applied on the source code of a module. They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools, and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript, or inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules!
中文翻译过来就是:
loader 用于对模块的源代码进行转换。loader 可以使你在 import 或“加载”模块时预处理文件。因此,loader 类似于其他构建工具中“任务(task)”,并提供了处理前端构建步骤的强大方法。loader 可以将文件从不同的语言(如 TypeScript)转换为 JavaScript,或将内联图像转换为 data URL。loader 甚至允许你直接在 JavaScript 模块中 import CSS文件!
从中,可以看出loader的强大作用,分析下:
总结一句话:loader, 加载的机器,形象的比喻下,就像一个豆浆机,放上你的原料,它就开始认真的工作了!
常用的loader
1、babel-loader
This package allows transpiling JavaScript files using Babel and webpack.
加载 ES2015+ 代码,然后使用 Babel 转译为 ES5
安装:
- npm install--save - dev babel - loader babel - core babel - preset - env webpack
使用:
- {
- test: /\.js$/,
- exclude: /node_modules/,
- loader: 'babel-loader'
- }
2、style-loader
Adds CSS to the DOM by injecting a
将模块的导出作为样式添加到 DOM 中
安装:
- npm install style - loader--save - dev
建议要与css-loader一起使用
使用:
- {
- test: /\.css$/,
- use: [
- 'style-loader',
- 'css-loader'
- ]
- }
3、css-loader
解析 CSS 文件后,使用 import 加载,并且返回 CSS 代码
安装:
- npm install css - loader--save - dev
使用:
- {
- test: /\.css$/,
- use: ['style-loader', 'css-loader']
- }
4、less-loader
加载和转译 LESS 文件
安装:
- npm install--save - dev less - loader less
使用:
- {
- test: /\.less$/,
- exclude: /node_modules/,
- use: ExtractTextPlugin.extract(['css-loader', 'less-loader'])
- }
5、url-loader
Loads files as base64 encoded URL
处理图片类文件,但如果文件小于限制,可以返回 data URL
安装:
- npm install--save - dev url - loader
使用:
- {
- test: /\.(jpg|jpeg|png|gif)$/,
- loader: 'url-loader',
- options: {
- limit: 8192
- }
- }
6、file-loader
Instructs webpack to emit the required object as file and to return its public URL
处理font/svg等,将文件发送到输出文件夹,并返回(相对)URL
安装:
- npm install file - loader--save - dev
使用:
- {
- test: /\.(woff|woff2|svg|eot|ttf)$/,
- use: 'file-loader'
- }
7、vue-loader
加载和转译 Vue 组件
安装:
- npm install--save - dev vue - loader vue vue - template - compiler
使用:
- {
- test: /\.vue$/,
- loader: 'vue-loader',
- options: {
- loaders: {
- less: ExtractTextPlugin.extract({
- use: ['css-loader', 'less-loader'],
- fallback: 'vue-style-loader'
- })
- }
- }
- }
至此,有关loader中所用的参数请移步官网查询解决,谢谢查阅!以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
来源: http://www.jb51.net/article/126811.htm