Skip to content

Commit

Permalink
fix(dev): transform import for commonjs dependencies (#837)
Browse files Browse the repository at this point in the history
* fix(dev): preserve named exports when optimizing cjs deps

* chore: delete my vscode config

* feat(dev): allow users to manually specify cjs named exports

* test: add test

* test: fix test

* test: fix test

* fix(dev): transform import for comm
onjs dependencies

* fix: delete unused code

* test: fix test

* chore: remove unused dep

* fix: remove unused config

* test: fix test

* fix: fix code style

* fix: remove console.log

* fix(dev): simplify dynamic import rewriting logic

* feat(dev): use cjs detection from @rollup/plugin-commonjs

* fix(dev): add exception handling

* fix: use official @rollup/plugin-commonjs

* fix: fix build error

* fix: better error handling

Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
csr632 and antfu committed Nov 24, 2020
1 parent ce633f4 commit 51aead4
Show file tree
Hide file tree
Showing 12 changed files with 338 additions and 13 deletions.
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"@rollup/plugin-commonjs": "^16.0.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^10.0.0",
"@rollup/pluginutils": "^4.0.0",
"@rollup/pluginutils": "^4.1.0",
"@types/koa": "^2.11.4",
"@types/lru-cache": "^5.1.0",
"@vue/compiler-dom": "^3.0.2",
Expand Down Expand Up @@ -135,6 +135,9 @@
"npm-run-all": "^4.1.5",
"postcss-nesting": "^7.0.1",
"preact": "^10.4.1",
"prop-types": "^15.7.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"prettier": "^2.2.0",
"pug": "^3.0.0",
"puppeteer": "^5.5.0",
Expand Down
7 changes: 5 additions & 2 deletions playground/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
<TestWasm />
</Suspense>
<TestScriptSetupStyleVars msg="Test message" />
<TestSyntax/>
<TestSyntax />
<TestCjsDepNamedExport />
</template>

<script>
Expand Down Expand Up @@ -62,6 +63,7 @@ import TestWebWorker from './worker/TestWorker.vue'
import TestWasm from './wasm/TestWasm.vue'
import TestScriptSetupStyleVars from './script-setup/TestScriptSetupStyleVars.vue'
import TestSyntax from './TestSyntax.vue'
import TestCjsDepNamedExport from './cjs-dep-named-export/TestCjsDepNamedExport.vue'
const App = {
components: {
Expand Down Expand Up @@ -92,7 +94,8 @@ const App = {
TestWebWorker,
TestWasm,
TestScriptSetupStyleVars,
TestSyntax
TestSyntax,
TestCjsDepNamedExport
}
}
export { App as default}
Expand Down
60 changes: 60 additions & 0 deletions playground/cjs-dep-named-export/TestCjsDepNamedExport.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<template>
<h2>Optimize cjs dep with named export</h2>
<p class="cjs-dep-named-export-static">
static import result: {{ staticImport }}
</p>
<p class="cjs-dep-named-export-dynamic">
dynamic import result: {{ dynamicImport }}
</p>
<button class="cjs-dep-named-export-dynamic-load" @click="loadDynamic()">
load dynamic
</button>
</template>

<script>
import { ref } from 'vue'
import React, { useState, createContext } from 'react'
import { default as React2, useState as useState2 } from 'react'
import * as ReactStar from 'react'
import PropTypes, { oneOfType } from 'prop-types'
export default {
setup() {
let staticImport
if (
isFunction(React.useState) &&
isFunction(useState) &&
isFunction(createContext) &&
isFunction(React2.useState) &&
isFunction(useState2) &&
isFunction(ReactStar.useState) &&
isFunction(PropTypes.oneOfType) &&
isFunction(oneOfType)
) {
staticImport = 'success'
} else {
staticImport = 'fail'
}
const dynamicImport = ref('dynamic not loaded')
function loadDynamic() {
// dynamic import cjs dep and get named-export
import('react-dom').then(({ render }) => {
dynamicImport.value = isFunction(render) ? 'success' : 'fail'
})
}
return {
staticImport,
dynamicImport,
loadDynamic
}
}
}
function isFunction(v) {
return typeof v === 'function'
}
</script>
3 changes: 3 additions & 0 deletions playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
"moment": "link:../node_modules/moment",
"@babel/runtime": "link:../node_modules/@babel/runtime",
"normalize.css": "link:../node_modules/normalize.css",
"react": "link:../node_modules/react",
"react-dom": "link:../node_modules/react-dom",
"prop-types": "link:../node_modules/prop-types",
"optimize-linked": "link:./optimize-linked",
"resolve-browser-field-test-package": "link:./resolve/browser-field",
"rewrite-optimized-test-package": "link:./resolve/rewrite-optimized/test-package",
Expand Down
51 changes: 51 additions & 0 deletions playground/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@
version "0.0.0"
uid ""

"js-tokens@^3.0.0 || ^4.0.0":
version "4.0.0"
resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==

"linked-dep@link:./optimize-linked/linked-dep":
version "0.0.0"
uid ""
Expand All @@ -18,6 +23,13 @@
version "0.0.0"
uid ""

loose-envify@^1.1.0, loose-envify@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf"
integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==
dependencies:
js-tokens "^3.0.0 || ^4.0.0"

"moment@link:../node_modules/moment":
version "0.0.0"
uid ""
Expand All @@ -26,10 +38,41 @@
version "0.0.0"
uid ""

object-assign@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863"
integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=

"optimize-linked@link:./optimize-linked":
version "0.0.0"
uid ""

prop-types@^15.6.2:
version "15.7.2"
resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5"
integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==
dependencies:
loose-envify "^1.4.0"
object-assign "^4.1.1"
react-is "^16.8.1"

"prop-types@link:../node_modules/prop-types":
version "0.0.0"
uid ""

"react-dom@link:../node_modules/react-dom":
version "0.0.0"
uid ""

react-is@^16.8.1:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==

"react@link:../node_modules/react":
version "0.0.0"
uid ""

regenerator-runtime@^0.13.4:
version "0.13.5"
resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.5.tgz#d878a1d094b4306d10b9096484b33ebd55e26697"
Expand All @@ -46,3 +89,11 @@ regenerator-runtime@^0.13.4:
"rewrite-unoptimized-test-package@link:./resolve/rewrite-unoptimized/test-package":
version "0.0.0"
uid ""

scheduler@^0.19.1:
version "0.19.1"
resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.19.1.tgz#4f3e2ed2c1a7d65681f4c854fa8c5a1ccb40f196"
integrity sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
30 changes: 30 additions & 0 deletions src/node/optimizer/entryAnalysisPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Plugin } from 'rollup'

export interface OptimizeAnalysisResult {
isCommonjs: { [name: string]: true }
}

export function entryAnalysisPlugin(): Plugin {
const analysis: OptimizeAnalysisResult = { isCommonjs: {} }
return {
name: 'vite:cjs-entry-named-export',
async generateBundle(options, bundles) {
Object.values(bundles).forEach((bundle) => {
if (bundle.type === 'chunk' && bundle.isEntry) {
if (bundle.facadeModuleId) {
const facadeInfo = this.getModuleInfo(bundle.facadeModuleId)
// this info is exposed by rollup commonjs plugin
if (facadeInfo?.meta?.commonjs?.isCommonJS) {
analysis.isCommonjs[bundle.name] = true
}
}
}
})
this.emitFile({
type: 'asset',
fileName: '_analysis.json',
source: JSON.stringify(analysis)
})
}
}
}
6 changes: 6 additions & 0 deletions src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
createDepAssetPlugin,
createDepAssetExternalPlugin
} from './pluginAssets'
import { entryAnalysisPlugin } from './entryAnalysisPlugin'

const debug = require('debug')('vite:optimize')

Expand Down Expand Up @@ -202,6 +203,7 @@ export async function optimizeDeps(
...rollupInputOptions,
plugins: [
createDepAssetExternalPlugin(resolver),
entryAnalysisPlugin(),
...(await createBaseRollupPlugins(root, resolver, config)),
createDepAssetPlugin(resolver, root),
...pluginsOptimizer
Expand All @@ -225,6 +227,10 @@ export async function optimizeDeps(
await fs.ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, chunk.code)
}
if (chunk.type === 'asset' && chunk.fileName === '_analysis.json') {
const filePath = path.join(cacheDir, chunk.fileName)
await fs.writeFile(filePath, chunk.source)
}
}

await fs.writeFile(hashPath, depHash)
Expand Down

0 comments on commit 51aead4

Please sign in to comment.