Skip to content

Commit

Permalink
some babel plugin cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott committed Jul 25, 2019
1 parent 5fc6306 commit 82b707d
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions assets/babel-plugin.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
const path = require('path');

// A lame copy-paste from src/index.ts
function getWebDependencyName(dep) {
return dep.replace(/\.js$/, '');
}

function rewriteBareModuleImport(imp, addMissingJsExtensions) {
const extname = addMissingJsExtensions && '.js';
if (imp.startsWith('/') || imp.startsWith('.')|| imp.startsWith('\\')) {
if (extname && !path.extname(imp)) imp += extname;
return imp;
function rewriteImport(imp, shouldAddMissingExtension) {
const isSourceImport = imp.startsWith('/') || imp.startsWith('.')|| imp.startsWith('\\');
if (!isSourceImport) {
return `/web_modules/${getWebDependencyName(imp)}.js`;
}
if (shouldAddMissingExtension && !path.extname(imp)) {
return imp + '.js';
}
return `/web_modules/${getWebDependencyName(imp)}.js`;
return imp;
}

module.exports = function pikaWebBabelTransform({types: t}, options) {
const addMissingJsExtensions = options.addMissingJsExtensions;
const rewriteBareModuleName = options.rewriteBareModuleName || rewriteBareModuleImport;
/**
* BABEL OPTIONS:
* extensionsOptional - Adds any missing JS extensions to local/relative imports. Support for these
* partial imports is missing in the browser and being phased out of Node.js, but
* this can be a useful option for migrating an old project to @pika/web.
*/
module.exports = function pikaWebBabelTransform({types: t}, {extensionsOptional}) {
return {
visitor: {
CallExpression(path, {file, opts}) {
Expand All @@ -32,7 +37,7 @@ module.exports = function pikaWebBabelTransform({types: t}, options) {


source.replaceWith(
t.stringLiteral(rewriteBareModuleName(source.node.value, addMissingJsExtensions)),
t.stringLiteral(rewriteImport(source.node.value, extensionsOptional)),
);
},
'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(path, {file, opts}) {
Expand All @@ -44,7 +49,7 @@ module.exports = function pikaWebBabelTransform({types: t}, options) {
}

source.replaceWith(
t.stringLiteral(rewriteBareModuleName(source.node.value, addMissingJsExtensions)),
t.stringLiteral(rewriteImport(source.node.value, extensionsOptional)),
);
},
},
Expand Down

0 comments on commit 82b707d

Please sign in to comment.