Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在图片的处理上有没有什么好的方案 #1550

Closed
lbb00 opened this issue Dec 17, 2018 · 9 comments
Closed

在图片的处理上有没有什么好的方案 #1550

lbb00 opened this issue Dec 17, 2018 · 9 comments

Comments

@lbb00
Copy link

lbb00 commented Dec 17, 2018

能否允许在image的src里直接引用相对路径。
在打包时,将image相对路径的图片和css中的图片,单独打包到一个文件夹中。
url替换为带有hash的图片路径。并支持添加cdn前缀。

或者各位在静态图片的处理上有没有什么好的方案,可以供参考一下?

@taro-bot
Copy link

taro-bot bot commented Dec 17, 2018

欢迎提交 Issue~

如果你提交的是 bug 报告,请务必遵循 Issue 模板的规范,尽量用简洁的语言描述你的问题,最好能提供一个稳定简单的复现。🙏🙏🙏

如果你的信息提供过于模糊或不足,或者已经其他 issue 已经存在相关内容,你的 issue 有可能会被关闭。

Good luck and happy coding~

@lbb00
Copy link
Author

lbb00 commented Dec 17, 2018

#998 这个issues提到的思路好像还可以?

@lbb00
Copy link
Author

lbb00 commented Dec 17, 2018

@wujjpp 能分享一下你们的方案么

@DiamondYuan
Copy link
Contributor

可以自己写一个 loader

@lbb00
Copy link
Author

lbb00 commented Dec 26, 2018

可以自己写一个 loader

希望能有一套完整的方案

@lbb00 lbb00 closed this as completed Jan 7, 2019
@wujjpp
Copy link
Contributor

wujjpp commented Jan 7, 2019

@loveonelong

我们现在就是自己写了2个loader: 一个用于处理css里面的url, 一个用于处理 js 中import 进来的image

config 可以参照 #998

babel-plugin-transform-image-to-url.js

/**
 * Created by Wu Jian Ping on 2018/11/1.
 */

const pathUtils = require('path') //eslint-disable-line
const utils = require('./utils') //eslint-disable-line

module.exports = function ({types: t}) {
  return {
    visitor: {
      VariableDeclarator(path, state){
        let node = path.node
        if (node && node.init) {
          if (utils.isImage(node.init.value) && !utils.isUrl(node.init.value)) {
            let source = pathUtils.join(utils.getAppPath(), 'src', node.init.value)
            let target = pathUtils.join(utils.getAppPath(), state.opts.staticDirectory, utils.getFileNameWithHash(source))
            utils.createDirIfNotExists(pathUtils.dirname(target))
            utils.copyFile(source, target)
            node.init = t.stringLiteral(state.opts.publicPath + pathUtils.basename(target))
          }
        }
      }
    }
  }
}

postcss-plugin-image-to-url.js

/**
 * Created by Wu Jian Ping on 2018/11/1.
 */

const postcss = require('postcss') //eslint-disable-line
const path = require('path') //eslint-disable-line
const utils = require('./utils') //eslint-disable-line

const URL_PATTERNS = [
  /(url\(\s*['"]?)([^"')]+)(["']?\s*\))/g,
  /(AlphaImageLoader\(\s*src=['"]?)([^"')]+)(["'])/g
]

const getPattern = decl => URL_PATTERNS.find((pattern) => pattern.test(decl.value))

module.exports = postcss.plugin('postcss-transform-url', (options) => {
  options = options || {}

  return function (styles, result) {
    const opts = result.opts
    const from = opts.from ? path.dirname(opts.from) : '.'

    styles.walkDecls(decl => {

      const isNotUrl = !utils.isUrl(decl.value)

      if (isNotUrl) {
        const pattern = getPattern(decl)

        if (!pattern) return

        decl.value = decl.value.replace(pattern, (matched, before, url, after) => {
          let index = url.indexOf('?')
          if (index !== -1) {
            url = url.substr(0, index)
          }
          let source = path.join(from, url)
          if (utils.isFont(url)) {
            let file = utils.getFile(source)
            let encodeStr = utils.encodeFile(file, 'base64', true)
            return `${before}${encodeStr}${after}`
          } else if (utils.isImage(url)) {
            let target = path.join(utils.getAppPath(), options.staticDirectory, utils.getFileNameWithHash(source))
            utils.createDirIfNotExists(path.dirname(target))
            utils.copyFile(source, target)
            return `${before}${options.publicPath}${path.basename(target)}${after}`
          }
        })
      }
    })
  }
})

utils.js

/**
 * Created by Wu Jian Ping on 2018/11/1.
 */

const fs = require('fs') // eslint-disable-line
const mkdirp  = require('mkdirp') // eslint-disable-line
const xxhashjs = require('xxhashjs') // eslint-disable-line
const path = require('path') // eslint-disable-line
const mime = require('mime') // eslint-disable-line

const REG_IMAGE = /\.(png|jpe?g|gif|bpm|svg)(\?.*)?$/
const REG_URL = /((http|ftp|https):\/\/)[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/
const REG_MEDIA = /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/
const REG_FONT = /\.(woff2?|eot|ttf|otf|svg)(\?.*)?$/

const copyFile = (source, target) =>  {
    fs.copyFileSync(source, target)
}

const createDirIfNotExists = dir => {
    mkdirp.sync(dir)
}

const getFileNameWithHash = fileName => {
    let buf = fs.readFileSync(fileName)
    let digest = xxhashjs.h32(0).update(buf).digest()
    let extName = path.extname(fileName)
    let fileNameWithoutExt = path.basename(fileName, extName)
    return `${fileNameWithoutExt}_${digest}${extName}`
}

const getAppPath = () => process.cwd()

const isImage = val => REG_IMAGE.test(val)

const isUrl = val => REG_URL.test(val)

const isMedia = val => REG_MEDIA.test(val)

const isFont = val => REG_FONT.test(val)

const getFile = filePath => {
    return {
        path: filePath,
        contents: fs.readFileSync(filePath),
        mimeType: mime.getType(filePath)
    };
}

const optimizedSvgEncode = (svgContent) => {
    const result = encodeURIComponent(svgContent)
        .replace(/%3D/g, '=')
        .replace(/%3A/g, ':')
        .replace(/%2F/g, '/')
        .replace(/%22/g, "'")
        .replace(/%2C/g, ',')
        .replace(/%3B/g, ';')

    // Lowercase the hex-escapes for better gzipping
    return result.replace(/(%[0-9A-Z]{2})/g, (matched, AZ) => {
        return AZ.toLowerCase()
    })
}

const encodeFile = (file, encodeType, shouldOptimizeSvgEncode) => {
    const dataMime = `data:${file.mimeType}`

    if (encodeType === 'base64') {
        return `${dataMime};base64,${file.contents.toString('base64')}`
    }

    const encodeFunc = encodeType === 'encodeURI' ? encodeURI : encodeURIComponent

    const content = file.contents.toString('utf8')
    // removing new lines
        .replace(/\n+/g, '')

    let encodedStr = (shouldOptimizeSvgEncode && encodeType === 'encodeURIComponent')
        ? optimizedSvgEncode(content)
        : encodeFunc(content)

    encodedStr = encodedStr
        .replace(/%20/g, ' ')
        .replace(/#/g, '%23')

    return `${dataMime},${encodedStr}`
};

module.exports = { // eslint-disable-line
    copyFile,
    createDirIfNotExists,
    getFileNameWithHash,
    getAppPath,
    isImage,
    isUrl,
    isMedia,
    isFont,
    getFile,
    encodeFile
}

@lbb00
Copy link
Author

lbb00 commented Jan 7, 2019

@wujjpp 谢谢分享

@wujjpp
Copy link
Contributor

wujjpp commented Jun 20, 2019

@patchBig trao的代码需要稍微改一下的

@cjz9032
Copy link

cjz9032 commented Jan 11, 2021

@patchBig trao的代码需要稍微改一下的

这里为什么还需要改呢 我看你上个PR不是merge了么

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants