打包后修改文件路径

 

  因为公司的需求,html和资源文件要放不同的服务,所以用相对路径是不可取的,在webpack找了大半天,也没找到怎么配置极其入口,所以在这我直接就在原有的基础文件本地修改了,代码如下:

  

// 修改index文件
const fs = require('fs');
const configCopy = {
  src: './dist/index.html',    //复制文件路径
  dist: './dist/prizewap.html',    //复制目标文件路径
  restr: ['href=.', 'src=".'],      //需要替换文本
  dstr: 'http://i0.beta.ulecdn.com/psbc/event/2018/0522',           //替换目标文本(文件名 + dstr)
} 


rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  webpack(webpackConfig, (err, stats) => {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    if (stats.hasErrors()) {
      console.log(chalk.red('  Build failed with errors.\n'))
      process.exit(1)
    }

    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))

    copy(configCopy.src, configCopy.dist)
  })
})


function copy(src, dist) {
  let readStream = fs.createReadStream(src);
  let writeStream = fs.createWriteStream(dist)
  readStream.setEncoding('utf-8');

  readStream.on('data', (chunk) => {
    let reg = '';
    let result = chunk;
    configCopy.restr.forEach(s => {
      reg = RegExp(s, 'g')
      console.log(s.substring(0, s.length-1));
      
      result = result.replace(reg, s.substring(0, s.length-1) + configCopy.dstr)
    });
    writeStream.write(result)
  })

  readStream.on('close', () => {
    console.log(' 添加路径成功');

  })

}

 自己写的修改文件,然后自动添加路径即可,然后把这个函数在webpack打包成功后调用即可

posted @ 2018-05-29 10:47  岁末博  阅读(686)  评论(0编辑  收藏  举报