Skip to content

Commit

Permalink
feature(preview): use is-module
Browse files Browse the repository at this point in the history
  • Loading branch information
xyc committed Apr 22, 2019
1 parent de57c51 commit bd0332b
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 14 deletions.
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -205,6 +205,7 @@
"@mdx-js/mdx": "^0.20.3",
"babel-plugin-transform-dynamic-import": "^2.1.0",
"gray-matter": "^4.0.2",
"is-module": "^1.0.0",
"path-is-inside": "^1.0.2",
"precinct": "^6.1.1",
"remark-parse": "^6.0.3",
Expand Down
23 changes: 9 additions & 14 deletions packages/extension/module-fetcher/module-fetcher.ts
@@ -1,6 +1,7 @@
import * as fs from 'fs';
import * as path from 'path';
import * as typescript from 'typescript';
import isModule from 'is-module';
import { Preview } from '../preview/preview-manager';
import { mdxTranspileAsync } from '../transpiler/mdx/mdx';
import { transformAsync as babelTransformAsync } from '../transpiler/babel';
Expand Down Expand Up @@ -149,27 +150,21 @@ export async function fetchLocal(request, isBare, parentId, preview: Preview) {
// }
// }

if (!fsPath.split(path.sep).includes('node_modules')) {
// Transform:
// - exclude node_modules
// - include file in node_modules only if it's es module
if (
!fsPath.split(path.sep).includes('node_modules') ||
isModule(code)
) {
console.log(`Transpiling: ${fsPath}`);
code = (await babelTransformAsync(code)).code;
} else {
// Only transpile npm packages if it's es module
// isEsModule function is from
// https://github.com/CompuIves/codesandbox-client/blob/13c9eda9bfaa38dec6a1699e31233bee388857bc/packages/app/src/sandbox/eval/utils/is-es-module.js
// Copyright (C) 2018 Ives van Hoorne
const isESModule = /(;|^)(import|export)(\s|{)/gm.test(code);
if (isESModule) {
console.log(`Transpiling: ${fsPath}`);
code = (await babelTransformAsync(code)).code;
} else {
code = code;
}
}

const dependencyNames = precinct(code);
// Figure out dependencies from code
// Don't care about dependency version ranges here, assuming user has already done
// yarn install or npm install.
const dependencyNames = precinct(code);
const dependencies = dependencyNames.map(dependencyName => {
// precinct returns undefined for dynamic import expression, TODO: refactor this
if (!dependencyName) {
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Expand Up @@ -2987,6 +2987,11 @@ is-lower-case@^1.1.0:
dependencies:
lower-case "^1.1.0"

is-module@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/is-module/-/is-module-1.0.0.tgz#3258fb69f78c14d5b815d664336b4cffb6441591"
integrity sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=

is-negated-glob@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/is-negated-glob/-/is-negated-glob-1.0.0.tgz#6910bca5da8c95e784b5751b976cf5a10fee36d2"
Expand Down

0 comments on commit bd0332b

Please sign in to comment.