文件处理

file-loader

file-loader 就是将文件(由于一般是图片文件为主,所以下面通常使用图片两字作为替代,方便理解。其他的包括字体文件等),在进行一些处理后(主要是处理文件名和路径),移动打包后的目录中。

默认情况下,生成的文件的文件名就是文件内容的 MD5 哈希值并会保留所引用资源的原始扩展名。

import img from './file.png'

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}
          }
        ]
      }
    ]
  }
}   

生成文件 file.png,输出到输出目录并返回 public URL。

"/public/path/0dcbbaa7013869e351f.png"

url-loader

url-loader 功能类似于 file-loader,但是在文件大小(单位 byte)低于指定的限制时,可以返回一个 DataURL。

import img from './image.png'

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  }
}

case-sensitive-paths-webpack-plugin

这个Webpack插件强制所有需要模块的完整路径与磁盘上的实际路径完全匹配。使用这个插件有助于缓解开发人员在OSX上工作时可能会与其他开发人员发生冲突,或者构建运行其他操作系统需要正确的大小写路径的框。OSX不遵循严格的路径大小写敏感性。

var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
 
var webpackConfig = {
    plugins: [
        new CaseSensitivePathsPlugin()
        // other plugins ...
    ]
    // other webpack config ...
}

json-loader

json文件加载器

{
    test: /\.json$/,
    use: [
        'json-loader'
    ]
}

xml-loader

xml文件加载器

{
    test: /\.xml$/,
    use: [
        'xml-loader'
    ]
}

csv-loader

csv/tsv文件加载器

{
    test: /\.(csv|tsv)$/,
    loader: 'csv-loader',
    options:
    {
        dynamicTyping: true,
        header: true,
        skipEmptyLines: true
    }
}

fs-extra

fs-extra模块是系统fs模块的扩展,提供了更多便利的API,如提供了promise支持。它还使用优雅的-fs来防止EMFILE错误。这应该是替换fs的一个下降。

const fs = require('fs-extra')
 
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
  .then(() => console.log('success!'))
  .catch(err => console.error(err))
 
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
  if (err) return console.error(err)
  console.log('success!')
})