`

webpack 使用加载器

阅读更多

加载器其实就是应用于你的程序的资源文件的转换器。它们将资源文件作为参数传入,然后返回新的资源。

例如,你可以使用加载器告诉webpack加载CoffeeScript文件或者JSX文件。

 

加载器特点:

  • 加载器可以链式调用,它们被应用于资源管道内。最后一个加载器产出JavaScript,其他的加载器则返回指定的格式(被传入下一个加载器)。
  • 加载器可以是同步的也可以是异步的。
  • 加载器运行在node.js中,可以做任何可能的事情。
  • 加载器接受查询参数,并用于配置加载器特性。
  • 加载器可以和配置中的扩展、正则绑定。
  • 加载器可以通过npm发布和安装。
  • 普通模块可以导出加载器,除了通过packag.json加载器加载的普通主模块。
  • 加载器可以被配置。
  • 插件可以给加载器添加更多新特性。
  • 加载器可以产出额外的任意文件。
  • 。。。。。

详解加载器

加载器都都是一些相似的模块。使用node.js兼容JavaScript的方式编写,并导出方法。通常情况下,你使用npm管理加载器,然而你也可以将加载器以文件的形式引入你的应用中。

 

引用加载器

  • 按照惯例(虽然不是必须的),加载器通常以XXX-loader的形式命名,XXX代表上下文名称。例如:josn-loader
  • 你可以使用全名引用加载器(例如:json-loader),也可以使用缩写名(例如:json)
  • 加载器的命名规则和优先级搜索顺序由WebPack配置API中的resolveLoader.moduleTemplates定义。
  • 加载器的命名规则是很有用的,特别是在使用require()声明引用加载器时。详见下面的使用规则

安装加载器

如果加载器是发不到npm上的,你可以通过下面的方式安装:

 

$ npm install xxx-loader --save

 或者

 

 

$ npm install xxx-loader --save-dev

 

 

使用加载器

这里有很多种方式使用加载器:

 

  • 直接使用require声明

备注:如果你希望你的代码和环境无关,请尽量不要使用这种方式。而应该使用配置文件配置加载器。

可以使用require声明(或者define,require.ensure,等等)定义加载器。使用'!'分隔加载器,每一个部分都相对于当前文件夹解析。

例如:

require("./loader!./dir/file.txt");
// => uses the file "loader.js" in the current directory to transform
//    "file.txt" in the folder "dir".

require("jade!./template.jade");
// => uses the "jade-loader" (that is installed from npm to "node_modules")
//    to transform the file "template.jade"

require("!style!css!less!bootstrap/less/bootstrap.less");
// => the file "bootstrap.less" in the folder "less" in the "bootstrap"
//    module (that is installed from github to "node_modules") is
//    transformed by the "less-loader". The result is transformed by the
//    "css-loader" and then by the "style-loader".

 

  • 通过配置文件配置

你可以通过配置文件将加载器和正则绑定:

{
    module: {
        loaders: [
            { test: /\.jade$/, loader: "jade" },
            // => "jade" loader is used for ".jade" files

            { test: /\.css$/, loader: "style!css" },
            // => "style" and "css" loader is used for ".css" files
            // Alternative syntax:
            { test: /\.css$/, loaders: ["style", "css"] },
        ]
    }
}

 

  • 通过命令行配置

你可以通过命令行将加载器和指定扩展后缀绑定:

$ webpack --module-bind jade --module-bind 'css=style!css'

 上面的命令设置使用“jade”加载器加载“.jade”文件,使用“style”和“css”加载器加载“.css”文件。

 

查询参数

加载器可以通过查询字符串(就像web中一样)传递查询参数。查询字符串被添加在“?”后,例如:url-loader?mimetype=image/png

备注:查询字符串的格式取决于加载器本身。具体格式请参考对应的加载器文档。大多数加载器都使用通常的查询格式(?key=value&key2=value2)和JSON对象格式(?{"key":"value","key2":"value2"})

 

  • 在require中
require("url-loader?mimetype=image/png!./file.png");

 

  • 在配置文件中
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }

 或者

{
    test: /\.png$/,
    loader: "url-loader",
    query: { mimetype: "image/png" }
}

 

  • 在命令行中
webpack --module-bind "png=url-loader?mimetype=image/png"

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics