Skip to content

Instantly share code, notes, and snippets.

@wssgcg1213

wssgcg1213/.webpackrc.js

Last active May 22, 2018
Embed
What would you like to do?
localize font
const axios = require('axios');
const { ConcatSource, RawSource } = require('webpack-sources');
const { createWriteStream } = require('fs');
const { dirname, join } = require('path');
const mkdirp = require('mkdirp');
module.exports = {
plugins: [
new class {
constructor() {
this.assets = {};
}
replace(source) {
const ALICDN_REG = /(https?:)?\/\/(i|at)\.alicdn\.com[^"^)]+\.(woff2?|svg|eot|ttf)/g;
let content = source.source();
content = content.replace(ALICDN_REG, $1 => {
const url = /^http/.test($1) ? $1 : 'https:' + $1;
const path = '/assets' + url.split('.com')[1];
if (!this.assets[path]) {
this.assets[path] = {
content: null,
url,
path
};
}
return (
(process.env.NODE_ENV === 'development' ? '/build' : '') + path
);
});
return new ConcatSource(content);
}
apply(compiler) {
if (process.env.NODE_ENV === 'development') {
return;
}
compiler.plugin('emit', (complication, done) => {
this.complication = complication;
const assets = Object.keys(complication.assets);
assets.forEach(name => {
if (/\.js$/.test(name) || /\.css$/.test(name)) {
complication.assets[name] = this.replace(
complication.assets[name]
);
}
});
Promise.all(
Object.keys(this.assets).map(path => {
const { url } = this.assets[path];
return axios(url, { responseType: 'stream' })
.then(res => res.data)
.then(content => {
this.assets[path].content = content;
// complication.assets[path] = new RawSource(content);
const dest = join(__dirname, 'build', path);
mkdirp.sync(dirname(dest));
content.pipe(createWriteStream(dest));
});
})
)
.then(() => {
done();
})
.catch(err => {
console.log(err);
});
});
}
}()
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment