UNPKG

vue-styleguidist

Version:
268 lines (256 loc) 14.7 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _typeof = require("@babel/runtime/helpers/typeof"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = _default; var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var path = _interopRequireWildcard(require("path")); var fs = _interopRequireWildcard(require("fs")); var _webpack = _interopRequireDefault(require("webpack")); var _terserWebpackPlugin = _interopRequireDefault(require("terser-webpack-plugin")); var _cleanWebpackPlugin = require("clean-webpack-plugin"); var _copyWebpackPlugin = _interopRequireDefault(require("copy-webpack-plugin")); var _miniHtmlWebpackPlugin = require("mini-html-webpack-plugin"); var _webpackFilterWarningsPlugin = _interopRequireDefault(require("webpack-filter-warnings-plugin")); var _miniHtmlWebpackTemplate = _interopRequireDefault(require("@vxna/mini-html-webpack-template")); var _webpackMerge = _interopRequireDefault(require("webpack-merge")); var _forEach = _interopRequireDefault(require("lodash/forEach")); var _isFunction = _interopRequireDefault(require("lodash/isFunction")); var _makeWebpackConfig = _interopRequireDefault(require("react-styleguidist/lib/scripts/make-webpack-config")); var _StyleguidistOptionsPlugin = _interopRequireDefault(require("react-styleguidist/lib/scripts/utils/StyleguidistOptionsPlugin")); var _mergeWebpackConfig = _interopRequireDefault(require("./utils/mergeWebpackConfig")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var RENDERER_REGEXP = /Renderer$/; var sourceDir = path.resolve(__dirname, '../client'); function _default(config, env) { var _config$editorConfig$, _config$editorConfig, _config$editorConfig$2, _webpack$version, _webpackConfig$plugin, _config$require$conca; /** this should be useful to test out webpack 5 when needed */ var webpack = process.env.VSG_WEBPACK_PATH ? require(process.env.VSG_WEBPACK_PATH) : _webpack["default"]; if (process.env.VSG_WEBPACK_PATH) { // eslint-disable-next-line no-console console.log("Using webpack from ".concat(process.env.VSG_WEBPACK_PATH)); } process.env.NODE_ENV = process.env.NODE_ENV || env; var isProd = env === 'production'; var template = (0, _isFunction["default"])(config.template) ? config.template : _miniHtmlWebpackTemplate["default"]; var templateContext = (0, _isFunction["default"])(config.template) ? {} : config.template; var htmlPluginOptions = { context: Object.assign({}, templateContext, { title: config.title, container: config.mountPointId, trimWhitespace: true }), template: template }; var webpackConfig = _objectSpread({ output: { path: config.styleguideDir, filename: 'build/[name].bundle.js', chunkFilename: 'build/[name].js' }, resolve: { extensions: ['.vue', '.js', '.jsx', '.json'], alias: { 'rsg-codemirror-theme.css': "codemirror/theme/".concat((_config$editorConfig$ = (_config$editorConfig = config.editorConfig) === null || _config$editorConfig === void 0 ? void 0 : (_config$editorConfig$2 = _config$editorConfig.theme) === null || _config$editorConfig$2 === void 0 ? void 0 : _config$editorConfig$2.split(' ')[0]) !== null && _config$editorConfig$ !== void 0 ? _config$editorConfig$ : 'default', ".css") } }, module: { rules: [{ type: 'javascript/auto', resourceQuery: /blockType=docs/, loader: require.resolve('../../lib/loaders/docs-loader.js') }] }, performance: { hints: false } }, (_webpack$version = webpack.version) !== null && _webpack$version !== void 0 && _webpack$version.startsWith('4.') ? { plugins: [new _webpackFilterWarningsPlugin["default"]({ exclude: /Critical dependency: require function is used in a way in which dependencies cannot be statically extracted/ })] } : { ignoreWarnings: [{ module: /@vue\/compiler-sfc/, message: /Critical dependency: require function is used in a way in which dependencies cannot be statically extracted/ }] }); webpackConfig.mode = env; if (config.webpackConfig) { webpackConfig = (0, _mergeWebpackConfig["default"])(webpackConfig, config.webpackConfig, env); } // check that the define variables are not set yet var definePluginsVariables = (_webpackConfig$plugin = webpackConfig.plugins) === null || _webpackConfig$plugin === void 0 ? void 0 : _webpackConfig$plugin.filter(function (plugin) { return plugin.constructor.name === 'DefinePlugin'; }).reduce(function (acc, plugin) { return acc.concat(Object.keys(plugin.definitions)); }, []); webpackConfig = (0, _webpackMerge["default"])(webpackConfig, { // we need to follow our own entry point entry: (_config$require$conca = config.require.concat([path.resolve(sourceDir, 'index')])) !== null && _config$require$conca !== void 0 ? _config$require$conca : path.resolve(sourceDir, 'index'), plugins: [ // in order to avoid collision with the preload plugins // that are loaded by the vue cli // we have to load these plugins last new _StyleguidistOptionsPlugin["default"](config), new _miniHtmlWebpackPlugin.MiniHtmlWebpackPlugin(htmlPluginOptions), new webpack.DefinePlugin(_objectSpread(_objectSpread({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), 'process.env.STYLEGUIDIST_ENV': JSON.stringify(env) }, definePluginsVariables !== null && definePluginsVariables !== void 0 && definePluginsVariables.includes('__VUE_OPTIONS_API__') || false ? {} : { __VUE_OPTIONS_API__: true }), definePluginsVariables !== null && definePluginsVariables !== void 0 && definePluginsVariables.includes('__VUE_PROD_DEVTOOLS__') ? {} : { __VUE_PROD_DEVTOOLS__: true }))] }); // To have the hot-reload work on vue-styleguide // the HMR has to be loaded after the html plugin. // Hence this piece added last to the list of plugins. if (isProd) { var optimization = config.minimize ? { minimizer: [new _terserWebpackPlugin["default"]({ parallel: true, cache: true, terserOptions: { ie8: false, ecma: 5, compress: { keep_fnames: true, warnings: false, /** * Disable reduce_funcs to keep Terser from inlining * Preact's VNode. If enabled, the 'new VNode()' is replaced * with a anonymous 'function(){}', which is problematic for * preact-compat, since it extends the VNode prototype to * accomodate React's API. */ reduce_funcs: false }, mangle: { keep_fnames: true } } })] } : { minimize: false }; webpackConfig = (0, _webpackMerge["default"])(webpackConfig, { output: { filename: 'build/bundle.[chunkhash:8].js', chunkFilename: 'build/[name].[chunkhash:8].js', publicPath: config.styleguidePublicPath }, plugins: [new _cleanWebpackPlugin.CleanWebpackPlugin({ verbose: config.verbose === true })].concat((0, _toConsumableArray2["default"])(config.assetsDir ? [new _copyWebpackPlugin["default"]([{ from: config.assetsDir }])] : [])), optimization: optimization }); } else { webpackConfig = (0, _webpackMerge["default"])({ output: { publicPath: config.styleguidePublicPath }, devServer: { publicPath: config.styleguidePublicPath, // Use 'ws' instead of 'sockjs-node' on server since we're using native // websockets in `webpackHotDevClient`. transportMode: 'ws', // Prevent a WS client from getting injected as we're already including // `webpackHotDevClient`. injectClient: false }, plugins: [new webpack.HotModuleReplacementPlugin(), new webpack.ProvidePlugin({ // Webpack 5 does no longer include a polyfill for this Node.js variable. // https://webpack.js.org/migrate/5/#run-a-single-build-and-follow-advice process: 'process/browser' })], entry: [require.resolve('react-dev-utils/webpackHotDevClient')] }, webpackConfig); } var RSG_COMPONENTS_ALIAS = 'rsg-components'; var RSG_COMPONENTS_ALIAS_DEFAULT = "".concat(RSG_COMPONENTS_ALIAS, "-default"); var webpackAlias = webpackConfig.resolve && webpackConfig.resolve.alias || {}; // Custom style guide components have priority over vsg components if (config.styleguideComponents) { (0, _forEach["default"])(config.styleguideComponents, function (filepath, name) { var fullName = name.match(RENDERER_REGEXP) ? "".concat(name.replace(RENDERER_REGEXP, ''), "/").concat(name) : name; webpackAlias["".concat(RSG_COMPONENTS_ALIAS, "/").concat(fullName)] = filepath; }); } // vue-styleguidist overridden components var sourceSrc = path.resolve(sourceDir, RSG_COMPONENTS_ALIAS); fs.readdirSync(sourceSrc).forEach(function (component) { webpackAlias["".concat(RSG_COMPONENTS_ALIAS, "/").concat(component)] = path.resolve(sourceSrc, component); // plus in order to avoid cirular references, add an extra ref to the defaults // so that custom components can reference their defaults webpackAlias["".concat(RSG_COMPONENTS_ALIAS_DEFAULT, "/").concat(component)] = webpackAlias["".concat(RSG_COMPONENTS_ALIAS, "/").concat(component)]; }); // For some components, the alias model is a little more complicated, // because we only override a part of the directory var custComp = ['slots/UsageTabButton', 'ReactComponent/ReactComponent', 'StyleGuide/StyleGuideRenderer']; var userCustomComponents = config.styleguideComponents || {}; var customComponents = custComp.reduce(function (acc, comp) { // unless the component is a user custom component var compParts = comp.split('/'); if (!userCustomComponents[comp] && !userCustomComponents[compParts[0]] && !userCustomComponents[compParts[1]]) { // set the alias to the prefixed Vsg folder instead of the Rsg original folder // This allows Vsg to use Rsg version of the component without conflicts but still // wrap it in a renderer specific to vue // NOTE: it is only useful if we don't want to copy the component over and only customize the renderer acc[comp] = "Vsg".concat(comp); } return acc; }, {}); if (config.codeSplit) { customComponents['Playground/Playground'] = 'PlaygroundAsync/PlaygroundAsync'; } customComponents.Preview = path.join('Preview', config.codeSplit ? 'PreviewAsync' : 'Preview'); var buildEditorComponentChain = function buildEditorComponentChain(cc) { var key = 'Editor'; // avoid codesplitting tiny prism only spli heavy codemirror if (config.codeSplit && !config.simpleEditor) { cc[key] = 'EditorAsync'; key = 'EditorStatic'; } // adapt compiled/raw format neede for precompiled preview if (config.codeSplit) { cc[key] = 'EditorPrecompiled'; key = 'EditorString'; } // add codebutton if asked for if (config.copyCodeButton) { cc[key] = 'EditorWithToolbar'; key = 'EditorNoTools'; } // if the user chose prism, load the prism editor instead of codemirror cc[key] = path.join('VsgEditor', config.simpleEditor ? 'EditorPrism' : 'Editor'); }; buildEditorComponentChain(customComponents); Object.keys(customComponents).forEach(function (key) { webpackAlias["".concat(RSG_COMPONENTS_ALIAS, "/").concat(key)] = path.resolve(sourceSrc, customComponents[key]); webpackAlias["".concat(RSG_COMPONENTS_ALIAS_DEFAULT, "/").concat(key)] = webpackAlias["".concat(RSG_COMPONENTS_ALIAS, "/").concat(key)]; }); // Add components folder alias at the end so users can override our components to customize the style guide // (their aliases should be before this one) var resolve = (0, _makeWebpackConfig["default"])(config, env).resolve; if (resolve && resolve.alias) { webpackAlias[RSG_COMPONENTS_ALIAS] = resolve.alias[RSG_COMPONENTS_ALIAS]; } // To avoid circular rendering when overriding existing components, // Create another alias, not overriden by users if (config.styleguideComponents) { webpackAlias[RSG_COMPONENTS_ALIAS_DEFAULT] = webpackAlias[RSG_COMPONENTS_ALIAS]; } if (config.compilerPackage) { webpackAlias['vue-inbrowser-compiler$'] = config.compilerPackage; } if (config.dangerouslyUpdateWebpackConfig) { webpackConfig = config.dangerouslyUpdateWebpackConfig(webpackConfig, env); } return webpackConfig; }