Comparing version 0.16.6 to 0.16.7
@@ -0,1 +1,22 @@ | ||
## [0.16.7](https://github.com/vuejs/vite/compare/v0.16.6...v0.16.7) (2020-05-22) | ||
### Bug Fixes | ||
* defaultRequestToFile should handle uncached node_modules request ([#230](https://github.com/vuejs/vite/issues/230)) ([7a3e822](https://github.com/vuejs/vite/commit/7a3e822597b94f8440e7436e3cc54a2764fff4eb)), closes [#228](https://github.com/vuejs/vite/issues/228) | ||
* disable cssCodeSplit in ssr build ([457f1f2](https://github.com/vuejs/vite/commit/457f1f2aca32f968f4ffe822633a2b4c49456fd4)) | ||
* do not attempt to rewrite css urls that are hash fragments ([029de6b](https://github.com/vuejs/vite/commit/029de6b30bfc307d4b02f28703cd8d73a706b1cd)) | ||
* ensure env vairable replacements are efficient for bundle size ([1be6121](https://github.com/vuejs/vite/commit/1be61219d1e253d6edec812ff7828b69d775c093)) | ||
* ensure rewrite middlewares have highest priority ([e741628](https://github.com/vuejs/vite/commit/e74162857ad33788f6fa02a4dca863aa7354fc76)) | ||
* fix entry resolving for packages with explicit exports ([c493629](https://github.com/vuejs/vite/commit/c4936290380891353de0581e432389310147a8e0)), closes [#227](https://github.com/vuejs/vite/issues/227) | ||
* only apply vite-specific global replacements to non-dep code ([b96ed68](https://github.com/vuejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2)) | ||
### Features | ||
* support built-in css preprocess ([#220](https://github.com/vuejs/vite/issues/220)) ([bef67f5](https://github.com/vuejs/vite/commit/bef67f50a56d190a0cd5fd2bcea94ad2d4f80185)) | ||
* support loading customize env variables from .env file ([#223](https://github.com/vuejs/vite/issues/223)) ([89fe0a9](https://github.com/vuejs/vite/commit/89fe0a9c912cb944e87556ca3cc344c6fac0fc0d)), closes [#213](https://github.com/vuejs/vite/issues/213) | ||
## [0.16.6](https://github.com/vuejs/vite/compare/v0.16.4...v0.16.6) (2020-05-21) | ||
@@ -2,0 +23,0 @@ |
import { Plugin } from 'rollup'; | ||
import { Transform } from '../config'; | ||
export declare const createBuildCssPlugin: (root: string, publicBase: string, assetsDir: string, minify?: boolean | "terser" | "esbuild" | undefined, inlineLimit?: number, cssCodeSplit?: boolean, transforms?: Transform[]) => Plugin; | ||
export declare const createBuildCssPlugin: (root: string, publicBase: string, assetsDir: string, minify?: boolean | "terser" | "esbuild" | undefined, inlineLimit?: number, cssCodeSplit?: boolean) => Plugin; |
@@ -8,31 +8,37 @@ "use strict"; | ||
const buildPluginAsset_1 = require("./buildPluginAsset"); | ||
const utils_1 = require("../utils"); | ||
const hash_sum_1 = __importDefault(require("hash-sum")); | ||
const cssUtils_1 = require("../utils/cssUtils"); | ||
const debug = require('debug')('vite:build:css'); | ||
const urlRE = /(url\(\s*['"]?)([^"')]+)(["']?\s*\))/; | ||
const cssInjectionMarker = `__VITE_CSS__`; | ||
const cssInjectionRE = /__VITE_CSS__\(\)/g; | ||
exports.createBuildCssPlugin = (root, publicBase, assetsDir, minify = false, inlineLimit = 0, cssCodeSplit = true, transforms = []) => { | ||
exports.createBuildCssPlugin = (root, publicBase, assetsDir, minify = false, inlineLimit = 0, cssCodeSplit = true) => { | ||
const styles = new Map(); | ||
const assets = new Map(); | ||
transforms = transforms.filter((t) => t.as === 'css'); | ||
return { | ||
name: 'vite:css', | ||
async transform(css, id) { | ||
let transformed = false; | ||
if (transforms.length) { | ||
const { path, query } = utils_1.parseWithQuery(id); | ||
for (const t of transforms) { | ||
if (t.test(path, query)) { | ||
css = await t.transform(css, true, true, path, query); | ||
transformed = true; | ||
break; | ||
if (id.endsWith('.css') || cssUtils_1.cssPreprocessLangRE.test(id)) { | ||
const result = await cssUtils_1.compileCss(root, id, { | ||
id: '', | ||
source: css, | ||
filename: path_1.default.basename(id), | ||
scoped: false, | ||
modules: id.endsWith('.module.css'), | ||
preprocessLang: id.replace(cssUtils_1.cssPreprocessLangRE, '$2') | ||
}); | ||
let modules; | ||
if (typeof result === 'string') { | ||
css = result; | ||
} | ||
else { | ||
if (result.errors.length) { | ||
console.error(`[vite] error applying css transforms: `); | ||
result.errors.forEach(console.error); | ||
} | ||
css = result.code; | ||
modules = result.modules; | ||
} | ||
} | ||
if (transformed || id.endsWith('.css')) { | ||
// process url() - register referenced files as assets | ||
// and rewrite the url to the resolved public path | ||
if (urlRE.test(css)) { | ||
if (cssUtils_1.urlRE.test(css)) { | ||
const fileDir = path_1.default.dirname(id); | ||
@@ -51,30 +57,2 @@ css = await cssUtils_1.rewriteCssUrls(css, async (rawUrl) => { | ||
} | ||
// postcss | ||
let modules; | ||
const postcssConfig = await utils_1.loadPostcssConfig(root); | ||
const expectsModule = id.endsWith('.module.css'); | ||
if (postcssConfig || expectsModule) { | ||
try { | ||
const result = await require('postcss')([ | ||
...((postcssConfig && postcssConfig.plugins) || []), | ||
...(expectsModule | ||
? [ | ||
require('postcss-modules')({ | ||
generateScopedName: `[local]_${hash_sum_1.default(id)}`, | ||
getJSON(_, json) { | ||
modules = json; | ||
} | ||
}) | ||
] | ||
: []) | ||
]).process(css, { | ||
...(postcssConfig && postcssConfig.options), | ||
from: id | ||
}); | ||
css = result.css; | ||
} | ||
catch (e) { | ||
console.error(`[vite] error applying postcss transforms: `, e); | ||
} | ||
} | ||
styles.set(id, css); | ||
@@ -81,0 +59,0 @@ return { |
import { Plugin } from 'rollup'; | ||
export declare const createReplacePlugin: (replacements: Record<string, string>, sourcemap: boolean) => Plugin; | ||
export declare const createReplacePlugin: (test: (id: string) => boolean, replacements: Record<string, string>, sourcemap: boolean) => Plugin; |
@@ -7,4 +7,3 @@ "use strict"; | ||
const magic_string_1 = __importDefault(require("magic-string")); | ||
const filter = /\.(j|t)sx?$/; | ||
exports.createReplacePlugin = (replacements, sourcemap) => { | ||
exports.createReplacePlugin = (test, replacements, sourcemap) => { | ||
const pattern = new RegExp('\\b(' + | ||
@@ -20,3 +19,3 @@ Object.keys(replacements) | ||
transform(code, id) { | ||
if (filter.test(id)) { | ||
if (test(id)) { | ||
const s = new magic_string_1.default(code); | ||
@@ -23,0 +22,0 @@ let hasReplaced = false; |
@@ -1,2 +0,2 @@ | ||
import { RollupOutput, Plugin } from 'rollup'; | ||
import { RollupOutput, Plugin, InputOptions } from 'rollup'; | ||
import { InternalResolver } from '../resolver'; | ||
@@ -8,2 +8,3 @@ import { BuildConfig } from '../config'; | ||
} | ||
export declare const onRollupWarning: InputOptions['onwarn']; | ||
/** | ||
@@ -10,0 +11,0 @@ * Creates non-application specific plugins that are shared between the main |
@@ -27,2 +27,8 @@ "use strict"; | ||
}; | ||
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]; | ||
exports.onRollupWarning = (warning, warn) => { | ||
if (!warningIgnoreList.includes(warning.code)) { | ||
warn(warning); | ||
} | ||
}; | ||
/** | ||
@@ -122,3 +128,3 @@ * Named exports detection logic from Snowpack | ||
const start = Date.now(); | ||
const { root = process.cwd(), base = '/', outDir = path_1.default.resolve(root, 'dist'), assetsDir = '_assets', assetsInlineLimit = 4096, cssCodeSplit = true, alias = {}, transforms = [], resolvers = [], rollupInputOptions = {}, rollupOutputOptions = {}, emitIndex = true, emitAssets = true, write = true, minify = true, silent = false, sourcemap = false, shouldPreload = null } = options; | ||
const { root = process.cwd(), base = '/', outDir = path_1.default.resolve(root, 'dist'), assetsDir = '_assets', assetsInlineLimit = 4096, cssCodeSplit = true, alias = {}, resolvers = [], rollupInputOptions = {}, rollupOutputOptions = {}, emitIndex = true, emitAssets = true, write = true, minify = true, silent = false, sourcemap = false, shouldPreload = null, env = {} } = options; | ||
let spinner; | ||
@@ -140,2 +146,7 @@ const msg = 'Building for production...'; | ||
const basePlugins = await createBaseRollupPlugins(root, resolver, options); | ||
env.NODE_ENV = 'production'; | ||
const envReplacements = Object.keys(env).reduce((replacements, key) => { | ||
replacements[`process.env.${key}`] = JSON.stringify(env[key]); | ||
return replacements; | ||
}, {}); | ||
// lazy require rollup so that we don't load it when only using the dev server | ||
@@ -148,7 +159,3 @@ // importing it just for the types | ||
treeshake: { moduleSideEffects: 'no-external' }, | ||
onwarn(warning, warn) { | ||
if (warning.code !== 'CIRCULAR_DEPENDENCY') { | ||
warn(warning); | ||
} | ||
}, | ||
onwarn: exports.onRollupWarning, | ||
...rollupInputOptions, | ||
@@ -163,10 +170,14 @@ plugins: [ | ||
// Vue templates are compiled into js and included in chunks. | ||
buildPluginReplace_1.createReplacePlugin({ | ||
'process.env.NODE_ENV': '"production"', | ||
'process.env.': `({}).`, | ||
__DEV__: 'false', | ||
buildPluginReplace_1.createReplacePlugin((id) => /\.(j|t)sx?$/.test(id), { | ||
...envReplacements, | ||
'process.env.': `({}).` | ||
}, sourcemap), | ||
// for vite spcific replacements, make sure to only apply them to | ||
// non-dependency code to avoid collision (e.g. #224 antd has __DEV__) | ||
buildPluginReplace_1.createReplacePlugin((id) => !id.includes('node_modules') && /\.(j|t)sx?$/.test(id), { | ||
__DEV__: `false`, | ||
__BASE__: JSON.stringify(publicBasePath) | ||
}, sourcemap), | ||
// vite:css | ||
buildPluginCss_1.createBuildCssPlugin(root, publicBasePath, assetsDir, minify, assetsInlineLimit, cssCodeSplit, transforms), | ||
buildPluginCss_1.createBuildCssPlugin(root, publicBasePath, assetsDir, minify, assetsInlineLimit, cssCodeSplit), | ||
// vite:asset | ||
@@ -275,2 +286,3 @@ buildPluginAsset_1.createBuildAssetPlugin(root, publicBasePath, assetsDir, assetsInlineLimit), | ||
emitAssets: false, | ||
cssCodeSplit: false, | ||
minify: false | ||
@@ -277,0 +289,0 @@ }); |
@@ -117,3 +117,3 @@ "use strict"; | ||
async function runServe(options) { | ||
const server = require('../dist').createServer(options); | ||
const server = require('./server').createServer(options); | ||
let port = options.port || 3000; | ||
@@ -164,3 +164,3 @@ const protocol = options.https ? 'https' : 'http'; | ||
try { | ||
await require('../dist').build(options); | ||
await require('./build').build(options); | ||
process.exit(0); | ||
@@ -176,3 +176,3 @@ } | ||
try { | ||
await require('../dist').optimizeDeps(options, true /* as cli command */); | ||
await require('./depOptimizer').optimizeDeps(options, true /* as cli command */); | ||
process.exit(0); | ||
@@ -179,0 +179,0 @@ } |
/// <reference types="node" /> | ||
import { ServerPlugin } from './server'; | ||
import { Resolver } from './resolver'; | ||
import { DotenvParseOutput } from 'dotenv'; | ||
import { Options as RollupPluginVueOptions } from 'rollup-plugin-vue'; | ||
import { CompilerOptions } from '@vue/compiler-sfc'; | ||
import { InputOptions as RollupInputOptions, OutputOptions as RollupOutputOptions, OutputChunk } from 'rollup'; | ||
import { ServerPlugin } from './server'; | ||
import { Resolver } from './resolver'; | ||
import { Transform } from './transform'; | ||
@@ -72,2 +73,6 @@ import { DepOptimizationOptions } from './depOptimizer'; | ||
}; | ||
/** | ||
* Environment variables . | ||
*/ | ||
env?: DotenvParseOutput; | ||
} | ||
@@ -74,0 +79,0 @@ export interface ServerConfig extends SharedConfig { |
@@ -12,2 +12,3 @@ "use strict"; | ||
const start = Date.now(); | ||
const cwd = process.cwd(); | ||
let config; | ||
@@ -17,6 +18,6 @@ let resolvedPath; | ||
if (configPath) { | ||
resolvedPath = path_1.default.resolve(process.cwd(), configPath); | ||
resolvedPath = path_1.default.resolve(cwd, configPath); | ||
} | ||
else { | ||
const jsConfigPath = path_1.default.resolve(process.cwd(), 'vite.config.js'); | ||
const jsConfigPath = path_1.default.resolve(cwd, 'vite.config.js'); | ||
if (fs_extra_1.default.existsSync(jsConfigPath)) { | ||
@@ -26,3 +27,3 @@ resolvedPath = jsConfigPath; | ||
else { | ||
const tsConfigPath = path_1.default.resolve(process.cwd(), 'vite.config.ts'); | ||
const tsConfigPath = path_1.default.resolve(cwd, 'vite.config.ts'); | ||
if (fs_extra_1.default.existsSync(tsConfigPath)) { | ||
@@ -76,2 +77,11 @@ isTS = true; | ||
} | ||
// load environment variables | ||
const envConfigPath = path_1.default.resolve(cwd, '.env'); | ||
if (fs_extra_1.default.existsSync(envConfigPath) && fs_extra_1.default.statSync(envConfigPath).isFile()) { | ||
const env = require('dotenv').config(); | ||
if (env.error) { | ||
throw env.error; | ||
} | ||
config.env = env.parsed; | ||
} | ||
require('debug')('vite:config')(`config resolved in ${Date.now() - start}ms`); | ||
@@ -78,0 +88,0 @@ config.__path = resolvedPath; |
@@ -85,3 +85,3 @@ "use strict"; | ||
} | ||
const pkgInfo = resolver_1.resolveNodeModuleEntry(root, id); | ||
const pkgInfo = resolver_1.resolveNodeModule(root, id); | ||
if (!pkgInfo) { | ||
@@ -91,8 +91,8 @@ debug(`skipping ${id} (cannot resolve entry)`); | ||
} | ||
const [entry, pkg] = pkgInfo; | ||
if (!resolver_1.supportedExts.includes(path_1.default.extname(entry))) { | ||
const { entryFilePath, pkg } = pkgInfo; | ||
if (!resolver_1.supportedExts.includes(path_1.default.extname(entryFilePath))) { | ||
debug(`skipping ${id} (entry is not js)`); | ||
return false; | ||
} | ||
const content = fs_extra_1.default.readFileSync(utils_1.resolveFrom(root, entry), 'utf-8'); | ||
const content = fs_extra_1.default.readFileSync(entryFilePath, 'utf-8'); | ||
const [imports, exports] = es_module_lexer_1.parse(content); | ||
@@ -169,3 +169,2 @@ if (!exports.length && !/export\s+\*\s+from/.test(content)) { | ||
const rollup = require('rollup'); | ||
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]; | ||
const bundle = await rollup.rollup({ | ||
@@ -175,7 +174,3 @@ input, | ||
treeshake: { moduleSideEffects: 'no-external' }, | ||
onwarn(warning, warn) { | ||
if (!warningIgnoreList.includes(warning.code)) { | ||
warn(warning); | ||
} | ||
}, | ||
onwarn: build_1.onRollupWarning, | ||
...config.rollupInputOptions, | ||
@@ -182,0 +177,0 @@ plugins: [ |
@@ -17,3 +17,9 @@ export interface Resolver { | ||
export declare function resolveOptimizedModule(root: string, id: string): string | undefined; | ||
export declare function resolveNodeModuleEntry(root: string, id: string): [string, any] | undefined; | ||
export declare function resolveNodeModule(root: string, id: string): string | undefined; | ||
interface NodeModuleInfo { | ||
entry: string; | ||
entryFilePath: string; | ||
pkg: any; | ||
} | ||
export declare function resolveNodeModule(root: string, id: string): NodeModuleInfo | undefined; | ||
export declare function resolveNodeModuleFile(root: string, id: string): string | undefined; | ||
export {}; |
@@ -15,6 +15,12 @@ "use strict"; | ||
if (serverPluginModuleResolve_1.moduleRE.test(publicPath)) { | ||
const moduleFilePath = serverPluginModuleResolve_1.idToFileMap.get(publicPath.replace(serverPluginModuleResolve_1.moduleRE, '')); | ||
if (moduleFilePath) { | ||
return moduleFilePath; | ||
const id = publicPath.replace(serverPluginModuleResolve_1.moduleRE, ''); | ||
const cachedModuleFilePath = serverPluginModuleResolve_1.idToFileMap.get(id); | ||
if (cachedModuleFilePath) { | ||
return cachedModuleFilePath; | ||
} | ||
const resolved = resolveNodeModuleFile(root, id); | ||
if (resolved) { | ||
serverPluginModuleResolve_1.idToFileMap.set(id, resolved); | ||
return resolved; | ||
} | ||
} | ||
@@ -108,5 +114,5 @@ return path_1.default.join(root, publicPath.slice(1)); | ||
} | ||
const pkgInfo = resolveNodeModuleEntry(root, id); | ||
const pkgInfo = resolveNodeModule(root, id); | ||
if (pkgInfo) { | ||
return pkgInfo[0]; | ||
return pkgInfo.entry; | ||
} | ||
@@ -146,5 +152,6 @@ // check and warn deep imports on optimized modules | ||
exports.resolveOptimizedModule = resolveOptimizedModule; | ||
const nodeModulesEntryMap = new Map(); | ||
function resolveNodeModuleEntry(root, id) { | ||
const cached = nodeModulesEntryMap.get(id); | ||
const nodeModulesInfoMap = new Map(); | ||
const nodeModulesFileMap = new Map(); | ||
function resolveNodeModule(root, id) { | ||
const cached = nodeModulesInfoMap.get(id); | ||
if (cached) { | ||
@@ -159,5 +166,27 @@ return cached; | ||
catch (e) { } | ||
if (!pkgPath) { | ||
// if the above resolve failed, it's either the package is not installed, | ||
// or the package has explicit exports field preventing us from resolving | ||
// its package.json. Try to resovle the package.json's path by sniffing | ||
// the node_modules in the path. | ||
try { | ||
const entryPath = utils_1.resolveFrom(root, id); | ||
if (entryPath) { | ||
const moduleIndex = entryPath.lastIndexOf(path_1.default.join(`node_modules`, id)); | ||
if (moduleIndex > 0) { | ||
pkgPath = path_1.default.join(entryPath.slice(0, moduleIndex), 'node_modules', id, 'package.json'); | ||
} | ||
} | ||
} | ||
catch (e) { } | ||
} | ||
if (pkgPath) { | ||
// if yes, this is a entry import. resolve entry file | ||
const pkg = JSON.parse(fs_1.default.readFileSync(pkgPath, 'utf-8')); | ||
let pkg; | ||
try { | ||
pkg = JSON.parse(fs_1.default.readFileSync(pkgPath, 'utf-8')); | ||
} | ||
catch (e) { | ||
return; | ||
} | ||
let entryPoint; | ||
@@ -180,13 +209,24 @@ if (pkg.exports) { | ||
} | ||
entryPoint = path_1.default.posix.join(id, '/', entryPoint); | ||
debug(`(node_module entry) ${id} -> ${entryPoint}`); | ||
const result = [entryPoint, pkg]; | ||
nodeModulesEntryMap.set(id, result); | ||
const entryFilePath = path_1.default.join(path_1.default.dirname(pkgPath), entryPoint); | ||
// save resolved entry file path using the deep import path as key | ||
// e.g. foo/dist/foo.js | ||
// this is the path raw imports will be rewritten to, and is what will | ||
// be passed to resolveNodeModuleFile(). | ||
entryPoint = path_1.default.posix.join(id, entryPoint); | ||
// save the resolved file path now so we don't need to do it again in | ||
// resolveNodeModuleFile() | ||
nodeModulesFileMap.set(entryPoint, entryFilePath); | ||
const result = { | ||
entry: entryPoint, | ||
entryFilePath, | ||
pkg | ||
}; | ||
nodeModulesInfoMap.set(id, result); | ||
return result; | ||
} | ||
} | ||
exports.resolveNodeModuleEntry = resolveNodeModuleEntry; | ||
const nodeModulesMap = new Map(); | ||
function resolveNodeModule(root, id) { | ||
const cached = nodeModulesMap.get(id); | ||
exports.resolveNodeModule = resolveNodeModule; | ||
function resolveNodeModuleFile(root, id) { | ||
const cached = nodeModulesFileMap.get(id); | ||
if (cached) { | ||
@@ -213,6 +253,6 @@ return cached; | ||
} | ||
nodeModulesMap.set(id, resolved); | ||
nodeModulesFileMap.set(id, resolved); | ||
return resolved; | ||
} | ||
exports.resolveNodeModule = resolveNodeModule; | ||
exports.resolveNodeModuleFile = resolveNodeModuleFile; | ||
//# sourceMappingURL=resolver.js.map |
@@ -44,8 +44,12 @@ "use strict"; | ||
const resolvedPlugins = [ | ||
// the import rewrite and html rewrite both take highest priority and runs | ||
// after all other middlewares have finished | ||
serverPluginModuleRewrite_1.moduleRewritePlugin, | ||
serverPluginHtml_1.htmlRewritePlugin, | ||
// user plugins | ||
...(Array.isArray(configureServer) ? configureServer : [configureServer]), | ||
serverPluginModuleResolve_1.moduleResolvePlugin, | ||
serverPluginProxy_1.proxyPlugin, | ||
serverPluginServiceWorker_1.serviceWorkerPlugin, | ||
serverPluginHmr_1.hmrPlugin, | ||
serverPluginModuleRewrite_1.moduleRewritePlugin, | ||
serverPluginModuleResolve_1.moduleResolvePlugin, | ||
serverPluginVue_1.vuePlugin, | ||
@@ -56,3 +60,2 @@ serverPluginCss_1.cssPlugin, | ||
serverPluginJson_1.jsonPlugin, | ||
serverPluginHtml_1.htmlPlugin, | ||
serverPluginAssets_1.assetPathPlugin, | ||
@@ -59,0 +62,0 @@ serverPluginServeStatic_1.serveStaticPlugin |
@@ -11,2 +11,4 @@ "use strict"; | ||
const cssUtils_1 = require("../utils/cssUtils"); | ||
const querystring_1 = __importDefault(require("querystring")); | ||
const chalk_1 = __importDefault(require("chalk")); | ||
const processedCSS = new Map(); | ||
@@ -17,7 +19,7 @@ exports.cssPlugin = ({ root, app, watcher, resolver, config }) => { | ||
// handle .css imports | ||
if (ctx.response.is('css') && | ||
if ((cssUtils_1.cssPreprocessLangRE.test(ctx.path) || ctx.response.is('css')) && | ||
// note ctx.body could be null if upstream set status to 304 | ||
ctx.body) { | ||
if (utils_1.isImportRequest(ctx)) { | ||
await processCss(ctx); | ||
await processCss(root, ctx); | ||
// we rewrite css with `?import` to a js module that inserts a style | ||
@@ -41,3 +43,3 @@ // tag linking to the actual raw url | ||
if (!processedCSS.has(ctx.path)) { | ||
await processCss(ctx); | ||
await processCss(root, ctx); | ||
} | ||
@@ -49,12 +51,27 @@ ctx.type = 'js'; | ||
}); | ||
// handle hmr | ||
const cssTransforms = config.transforms | ||
? config.transforms.filter((t) => t.as === 'css') | ||
: []; | ||
watcher.on('change', (file) => { | ||
if (file.endsWith('.css') || cssTransforms.some((t) => t.test(file, {}))) { | ||
if (file.endsWith('.css') || cssUtils_1.cssPreprocessLangRE.test(file)) { | ||
if (serverPluginVue_1.srcImportMap.has(file)) { | ||
// this is a vue src import, skip | ||
// handle HMR for <style src="xxx.css"> | ||
// it cannot be handled as simple css import because it may be scoped | ||
const styleImport = serverPluginVue_1.srcImportMap.get(file); | ||
serverPluginVue_1.vueCache.del(file); | ||
const publicPath = utils_1.cleanUrl(styleImport); | ||
const index = querystring_1.default.parse(styleImport.split('?', 2)[1]).index; | ||
console.log(chalk_1.default.green(`[vite:hmr] `) + `${publicPath} updated. (style)`); | ||
watcher.send({ | ||
type: 'vue-style-update', | ||
path: publicPath, | ||
index: Number(index), | ||
id: `${hash_sum_1.default(publicPath)}-${index}`, | ||
timestamp: Date.now() | ||
}); | ||
return; | ||
} | ||
// handle HMR for module.css | ||
// it cannot process with normal css, the class which in module.css maybe removed | ||
if (file.endsWith('.module.css')) { | ||
watcher.handleJSReload(file, Date.now()); | ||
return; | ||
} | ||
const publicPath = resolver.fileToRequest(file); | ||
@@ -72,35 +89,24 @@ const id = hash_sum_1.default(publicPath); | ||
}); | ||
async function processCss(ctx) { | ||
async function processCss(root, ctx) { | ||
let css = (await utils_1.readBody(ctx.body)); | ||
let modules; | ||
const postcssConfig = await utils_1.loadPostcssConfig(root); | ||
const expectsModule = ctx.path.endsWith('.module.css'); | ||
// postcss processing | ||
if (postcssConfig || expectsModule) { | ||
try { | ||
css = (await require('postcss')([ | ||
...((postcssConfig && postcssConfig.plugins) || []), | ||
...(expectsModule | ||
? [ | ||
require('postcss-modules')({ | ||
generateScopedName: `[local]_${hash_sum_1.default(ctx.path)}`, | ||
getJSON(_, json) { | ||
modules = json; | ||
} | ||
}) | ||
] | ||
: []) | ||
]).process(css, { | ||
...(postcssConfig && postcssConfig.options), | ||
from: resolver.requestToFile(ctx.path) | ||
})).css; | ||
} | ||
catch (e) { | ||
console.error(`[vite] error applying postcss transforms: `, e); | ||
} | ||
const result = await cssUtils_1.compileCss(root, ctx.path, { | ||
id: '', | ||
source: css, | ||
filename: resolver.requestToFile(ctx.path), | ||
scoped: false, | ||
modules: ctx.path.endsWith('.module.css'), | ||
preprocessLang: ctx.path.replace(cssUtils_1.cssPreprocessLangRE, '$2') | ||
}); | ||
if (typeof result === 'string') { | ||
processedCSS.set(ctx.path, { css }); | ||
return; | ||
} | ||
css = await cssUtils_1.rewriteCssUrls(css, ctx.path); | ||
if (result.errors.length) { | ||
console.error(`[vite] error applying css transforms: `); | ||
result.errors.forEach(console.error); | ||
} | ||
result.code = await cssUtils_1.rewriteCssUrls(result.code, ctx.path); | ||
processedCSS.set(ctx.path, { | ||
css, | ||
modules | ||
css: result.code, | ||
modules: result.modules | ||
}); | ||
@@ -107,0 +113,0 @@ } |
@@ -37,2 +37,3 @@ "use strict"; | ||
const slash_1 = __importDefault(require("slash")); | ||
const cssUtils_1 = require("../utils/cssUtils"); | ||
exports.debugHmr = require('debug')('vite:hmr'); | ||
@@ -87,6 +88,2 @@ exports.hmrAcceptanceMap = new Map(); | ||
watcher.send = send; | ||
// exclude files declared as css by user transforms | ||
const cssTransforms = config.transforms | ||
? config.transforms.filter((t) => t.as === 'css') | ||
: []; | ||
watcher.on('change', async (file) => { | ||
@@ -97,3 +94,3 @@ const timestamp = Date.now(); | ||
} | ||
else if (!(file.endsWith('.css') || cssTransforms.some((t) => t.test(file, {})))) { | ||
else if (!(file.endsWith('.css') || cssUtils_1.cssPreprocessLangRE.test(file))) { | ||
// everything except plain .css are considered HMR dependencies. | ||
@@ -100,0 +97,0 @@ // plain css has its own HMR logic in ./serverPluginCss.ts. |
import { ServerPlugin } from './index'; | ||
export declare const htmlPlugin: ServerPlugin; | ||
export declare const htmlRewritePlugin: ServerPlugin; |
@@ -16,5 +16,6 @@ "use strict"; | ||
const rewriteHtmlPluginCache = new lru_cache_1.default({ max: 20 }); | ||
exports.htmlPlugin = ({ root, app, watcher, resolver }) => { | ||
exports.htmlRewritePlugin = ({ root, app, watcher, resolver, config }) => { | ||
// inject __DEV__ and process.env.NODE_ENV flags | ||
// since some ESM builds expect these to be replaced by the bundler | ||
const { env = {} } = config; | ||
const devInjectionCode = `\n<script type="module">\n` + | ||
@@ -24,3 +25,6 @@ `import "${serverPluginHmr_1.hmrClientPublicPath}"\n` + | ||
`window.__BASE__ = '/'\n` + | ||
`window.process = { env: { NODE_ENV: 'development' }}\n` + | ||
`window.process = { env: ${JSON.stringify({ | ||
...env, | ||
NODE_ENV: 'development' | ||
})}}\n` + | ||
`</script>\n`; | ||
@@ -27,0 +31,0 @@ const scriptRE = /(<script\b[^>]*>)([\s\S]*?)<\/script>/gm; |
@@ -54,3 +54,3 @@ "use strict"; | ||
} | ||
const nodeModulePath = resolver_1.resolveNodeModule(root, id); | ||
const nodeModulePath = resolver_1.resolveNodeModuleFile(root, id); | ||
if (nodeModulePath) { | ||
@@ -57,0 +57,0 @@ return serve(id, nodeModulePath, 'node_modules'); |
@@ -14,3 +14,2 @@ "use strict"; | ||
const esbuildService_1 = require("../esbuildService"); | ||
const querystring_1 = __importDefault(require("querystring")); | ||
const serverPluginServeStatic_1 = require("./serverPluginServeStatic"); | ||
@@ -86,20 +85,2 @@ const cssUtils_1 = require("../utils/cssUtils"); | ||
}); | ||
// handle HMR for <style src="xxx.css"> | ||
// it cannot be handled as simple css import because it may be scoped | ||
watcher.on('change', (file) => { | ||
const styleImport = exports.srcImportMap.get(file); | ||
if (styleImport) { | ||
exports.vueCache.del(file); | ||
const publicPath = utils_1.cleanUrl(styleImport); | ||
const index = querystring_1.default.parse(styleImport.split('?', 2)[1]).index; | ||
console.log(chalk_1.default.green(`[vite:hmr] `) + `${publicPath} updated. (style)`); | ||
watcher.send({ | ||
type: 'vue-style-update', | ||
path: publicPath, | ||
index: Number(index), | ||
id: `${hash_sum_1.default(publicPath)}-${index}`, | ||
timestamp: Date.now() | ||
}); | ||
} | ||
}); | ||
}; | ||
@@ -266,23 +247,11 @@ async function resolveSrcImport(block, ctx, resolver) { | ||
const start = Date.now(); | ||
const id = hash_sum_1.default(publicPath); | ||
const postcssConfig = await utils_1.loadPostcssConfig(root); | ||
const { compileStyleAsync, generateCodeFrame } = resolveVue_1.resolveCompiler(root); | ||
const result = await compileStyleAsync({ | ||
const { generateCodeFrame } = resolveVue_1.resolveCompiler(root); | ||
const result = (await cssUtils_1.compileCss(root, publicPath, { | ||
source: style.content, | ||
filename, | ||
id: `data-v-${id}`, | ||
id: ``, | ||
scoped: style.scoped != null, | ||
modules: style.module != null, | ||
modulesOptions: { | ||
generateScopedName: `[local]_${id}` | ||
}, | ||
preprocessLang: style.lang, | ||
preprocessCustomRequire: (id) => require(utils_1.resolveFrom(root, id)), | ||
...(postcssConfig | ||
? { | ||
postcssOptions: postcssConfig.options, | ||
postcssPlugins: postcssConfig.plugins | ||
} | ||
: {}) | ||
}); | ||
preprocessLang: style.lang | ||
})); | ||
if (result.errors.length) { | ||
@@ -321,3 +290,2 @@ console.error(chalk_1.default.red(`\n[vite] SFC style compilation error: `)); | ||
} | ||
// rewrite relative urls | ||
result.code = await cssUtils_1.rewriteCssUrls(result.code, publicPath); | ||
@@ -324,0 +292,0 @@ cached = cached || { styles: [] }; |
@@ -5,6 +5,2 @@ import { ServerPlugin } from './server'; | ||
export interface Transform { | ||
/** | ||
* @default 'js' | ||
*/ | ||
as?: 'js' | 'css'; | ||
test: (path: string, query: ParsedQuery) => boolean; | ||
@@ -11,0 +7,0 @@ transform: (code: string, |
@@ -10,3 +10,3 @@ "use strict"; | ||
if (t.test(ctx.path, ctx.query)) { | ||
ctx.type = t.as || 'js'; | ||
ctx.type = 'js'; | ||
if (ctx.body) { | ||
@@ -26,3 +26,2 @@ const code = await utils_1.readBody(ctx.body); | ||
function createBuildJsTransformPlugin(transforms) { | ||
transforms = transforms.filter((t) => t.as === 'js' || !t.as); | ||
return { | ||
@@ -29,0 +28,0 @@ name: 'vite:transforms', |
@@ -0,3 +1,7 @@ | ||
import { SFCAsyncStyleCompileOptions, SFCStyleCompileResults } from '@vue/compiler-sfc'; | ||
export declare const urlRE: RegExp; | ||
export declare const cssPreprocessLangRE: RegExp; | ||
declare type Replacer = (url: string) => string | Promise<string>; | ||
export declare function rewriteCssUrls(css: string, replacerOrBase: string | Replacer): Promise<string>; | ||
export declare function compileCss(root: string, publicPath: string, { source, filename, scoped, modules, preprocessLang }: SFCAsyncStyleCompileOptions): Promise<SFCStyleCompileResults | string>; | ||
export {}; |
@@ -9,3 +9,7 @@ "use strict"; | ||
const pathUtils_1 = require("./pathUtils"); | ||
const urlRE = /(url\(\s*['"]?)([^"')]+)(["']?\s*\))/; | ||
const resolveVue_1 = require("./resolveVue"); | ||
const resolvePostCssConfig_1 = require("./resolvePostCssConfig"); | ||
const hash_sum_1 = __importDefault(require("hash-sum")); | ||
exports.urlRE = /(url\(\s*['"]?)([^"')]+)(["']?\s*\))/; | ||
exports.cssPreprocessLangRE = /(.+).(less|sass|scss|styl|stylus)$/; | ||
function rewriteCssUrls(css, replacerOrBase) { | ||
@@ -21,5 +25,7 @@ let replacer; | ||
} | ||
return transformUtils_1.asyncReplace(css, urlRE, async (match) => { | ||
return transformUtils_1.asyncReplace(css, exports.urlRE, async (match) => { | ||
const [matched, before, rawUrl, after] = match; | ||
if (pathUtils_1.isExternalUrl(rawUrl) || rawUrl.startsWith('data:')) { | ||
if (pathUtils_1.isExternalUrl(rawUrl) || | ||
rawUrl.startsWith('data:') || | ||
rawUrl.startsWith('#')) { | ||
return matched; | ||
@@ -31,2 +37,30 @@ } | ||
exports.rewriteCssUrls = rewriteCssUrls; | ||
async function compileCss(root, publicPath, { source, filename, scoped, modules, preprocessLang }) { | ||
const id = hash_sum_1.default(publicPath); | ||
const postcssConfig = await resolvePostCssConfig_1.loadPostcssConfig(root); | ||
const { compileStyleAsync } = resolveVue_1.resolveCompiler(root); | ||
if (publicPath.endsWith('.css') && !modules && !postcssConfig) { | ||
// no need to invoke compile for plain css if no postcss config is present | ||
return source; | ||
} | ||
return await compileStyleAsync({ | ||
source, | ||
filename, | ||
id: `data-v-${id}`, | ||
scoped, | ||
modules, | ||
modulesOptions: { | ||
generateScopedName: `[local]_${id}` | ||
}, | ||
preprocessLang: preprocessLang, | ||
preprocessCustomRequire: (id) => require(pathUtils_1.resolveFrom(root, id)), | ||
...(postcssConfig | ||
? { | ||
postcssOptions: postcssConfig.options, | ||
postcssPlugins: postcssConfig.plugins | ||
} | ||
: {}) | ||
}); | ||
} | ||
exports.compileCss = compileCss; | ||
//# sourceMappingURL=cssUtils.js.map |
{ | ||
"name": "vite", | ||
"version": "0.16.6", | ||
"version": "0.16.7", | ||
"license": "MIT", | ||
@@ -70,2 +70,3 @@ "author": "Evan You", | ||
"debug": "^4.1.1", | ||
"dotenv": "^8.2.0", | ||
"es-module-lexer": "^0.3.18", | ||
@@ -72,0 +73,0 @@ "esbuild": "^0.3.2", |
# vite ⚡ | ||
[![vuejs](https://circleci.com/gh/vuejs/vite.svg?style=shield)](https://app.circleci.com/pipelines/github/vuejs/vite) [![Build status](https://ci.appveyor.com/api/projects/status/a6gd7l0s0wysn3qm/branch/master?svg=true)](https://ci.appveyor.com/project/yyx990803/vite/branch/master) | ||
[![vuejs](https://circleci.com/gh/vitejs/vite.svg?style=shield)](https://app.circleci.com/pipelines/github/vuejs/vite) [![Build status](https://ci.appveyor.com/api/projects/status/0q4j8062olbcs71l/branch/master?svg=true)](https://ci.appveyor.com/project/yyx990803/vite/branch/master) | ||
@@ -189,4 +189,8 @@ Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with [Rollup](https://rollupjs.org/) for production. | ||
Note importing CSS / preprocessor files from `.js` files, and HMR from imported pre-processor files are currently not supported, but can be in the future. | ||
Or import them from JavaScript: | ||
```js | ||
import './style.scss' | ||
``` | ||
### JSX | ||
@@ -193,0 +197,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
247175
4642
389
41
+ Addeddotenv@^8.2.0
+ Addeddotenv@8.6.0(transitive)