Skip to content

Instantly share code, notes, and snippets.

@wssgcg1213
Last active May 22, 2018 07:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wssgcg1213/813083b31806ad75c6bd88fc715d6f36 to your computer and use it in GitHub Desktop.
Save wssgcg1213/813083b31806ad75c6bd88fc715d6f36 to your computer and use it in GitHub Desktop.
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