babel-plugin-transform-assets-import-to-string
Version:
Babel plugin that transforms image assets import and requires to urls / cdn
77 lines (64 loc) • 1.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.defaultOptions = undefined;
var _transform = require('./transform');
var _transform2 = _interopRequireDefault(_transform);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const defaultOptions = {
baseUri: '',
extensions: ['.gif', '.jpeg', '.jpg', '.png', '.svg'],
flatten: false
};
function isRequireStatement(p) {
const callee = p.get('callee');
return callee.isIdentifier() && callee.equals('name', 'require');
}
function isValidArgument(p) {
const arg = p.get('arguments')[0];
return arg && arg.isStringLiteral();
}
function initOptions(cache, state) {
if (cache) {
return cache;
}
return Object.assign({}, defaultOptions, state.opts);
}
function transformAssets({ types: t }) {
return {
pre() {
this.optionCache = null;
},
post() {
this.optionCache = null;
},
visitor: {
ImportDeclaration(p, state) {
this.optionCache = initOptions(this.optionCache, state);
(0, _transform2.default)({
path: p,
types: t,
filename: state.file.opts.filename,
value: p.node.source.value,
callee: 'import'
}, this.optionCache);
},
CallExpression(p, state) {
if (isRequireStatement(p) && isValidArgument(p)) {
const arg = p.get('arguments')[0];
this.optionCache = initOptions(this.optionCache, state);
(0, _transform2.default)({
path: p,
types: t,
filename: state.file.opts.filename,
value: arg.node.value,
callee: 'require'
}, this.optionCache);
}
}
}
};
}
exports.defaultOptions = defaultOptions;
exports.default = transformAssets;