美文网首页Webpack 官方文档翻译
05 - 使用加载器 - Webpack 官方文档翻译 Get

05 - 使用加载器 - Webpack 官方文档翻译 Get

作者: 勤劳的悄悄 | 来源:发表于2016-07-04 11:27 被阅读78次

    什么是加载器

    加载器本质上也是个 Javascript 模块,他的功能是将各种资源转换成易于使用的形式

    加载器的特征

    • 加载器可以链式调用,最后一个加载器必须返回 Javascript
    • 加载器可以是同步的,也可以是异步的
    • 加载器通过 Node.js 运行,因此可以做操作系统权限下的任何事情
    • 加载器接收参数,英此时可配置的
    • 加载器可以用正在表达式配置
    • 加载器通过 npm 发布和安装
    • 不仅可以在配置文件中使用加载器,也可以在代码中直接导入加载器模块
    • 其他特征

    解析

    加载器本质上就是个模块,可以想模块一样使用它

    命名约定

    一般加载器的命名格式为 XXX-loader,其中 XXX 表示要处理的资源类型,比如 json-loader

    既可以用完整命名引用加载器 (比如 json-loader),也可以用短名称引用 (比如 json)

    安装

    通过 npm 安装

    $ npm install xxx-loader --save
    

    或者

    $ npm install xxx-loader --save-dev
    

    使用方法

    有三种方式来使用加载器

    • 在代码中通过 require 语句直接调用
    • 通过配置文件使用
    • 在命令行中使用

    require 方式

    • 使用感叹号 ! 将加载器和资源分隔开
    • 路径是相对于当前位置的相对路径
    
    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"
    //    If configuration has some transforms bound to the file, they will still be applied.
    
    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".
    //    If configuration has some transforms bound to the file, they will not be applied.
    

    配置文件方式

    在配置文件中,可以使用正则表达式,让加载器处理某种类型的所有文件

    {
        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 文件,使用 stylecss 加载器处理 .css 文件

    参数

    可以给加载器传入参数,格式和 Web 中的查询字符串相同

    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"
    

    相关文章

      网友评论

        本文标题:05 - 使用加载器 - Webpack 官方文档翻译 Get

        本文链接:https://www.haomeiwen.com/subject/zbvcjttx.html