How to use @sanity/server - 10 common examples

To help you get started, we’ve selected a few @sanity/server examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sanity-io / sanity / packages / @sanity / core / src / actions / build / buildStaticAssets.js View on Github external
{...compilationConfig, hashes: chunkMap},
      {
        scripts: ['vendor.bundle.js', 'app.bundle.js'].map(asset => {
          const assetPath = absoluteMatch.test(asset) ? asset : `js/${asset}`
          return {
            path: assetPath,
            hash: chunkMap[assetPath] || chunkMap[asset]
          }
        })
      }
    )

    // Write index file to output destination
    await fse.writeFile(
      path.join(outputDir, 'index.html'),
      `${ReactDOM.renderToStaticMarkup(doc)}`
    )

    // Print build output, optionally stats if requested
    bundle.stats.warnings.forEach(output.print)
    spin.text = `Building index document (${Date.now() - indexStart}ms)`
    spin.succeed()

    if (flags.stats) {
      output.print('\nLargest modules (unminified, uncompressed sizes):')
      sortModulesBySize(bundle.stats.modules)
        .slice(0, 10)
        .forEach(module => output.print(`[${filesize(module.size)}] ${module.name}`))
    }

    // Now compress the JS bundles
    if (!compilationConfig.skipMinify) {
github sanity-io / sanity / packages / storybook / webpack.config.js View on Github external
module.exports = (storyWpConfig, configType) => {
  /* eslint-disable strict */

  'use strict'

  const sanityWpConfig = sanityServer.getWebpackBaseConfig({
    basePath: __dirname,
    commonChunkPlugin: false
  })

  sanityWpConfig.module = sanityWpConfig.module || {loaders: []}

  if (configType.toLowerCase() === 'development') {
    sanityWpConfig.module.loaders = sanityServer.applyStaticLoaderFix(sanityWpConfig, {
      httpHost: 'localhost',
      httpPort: 9001,
      staticPath: './static'
    })
  }

  return Object.assign({}, sanityWpConfig, storyWpConfig, {
    plugins: [].concat(storyWpConfig.plugins, sanityWpConfig.plugins || []),
    resolve: Object.assign({}, storyWpConfig.resolve, sanityWpConfig.resolve, {
      alias: Object.assign({}, storyWpConfig.resolve.alias || {}, sanityWpConfig.resolve.alias || {})
    }),
    module: Object.assign({}, storyWpConfig.module, sanityWpConfig.module, {
      loaders: [].concat(storyWpConfig.module.loaders, sanityWpConfig.module.loaders)
    })
  })
}
github sanity-io / sanity / packages / storybook / webpack.config.js View on Github external
module.exports = (storyWpConfig, configType) => {
  /* eslint-disable strict */

  'use strict'

  const sanityWpConfig = sanityServer.getWebpackBaseConfig({
    basePath: __dirname,
    commonChunkPlugin: false
  })

  sanityWpConfig.module = sanityWpConfig.module || {loaders: []}

  if (configType.toLowerCase() === 'development') {
    sanityWpConfig.module.loaders = sanityServer.applyStaticLoaderFix(sanityWpConfig, {
      httpHost: 'localhost',
      httpPort: 9001,
      staticPath: './static'
    })
  }

  return Object.assign({}, sanityWpConfig, storyWpConfig, {
    plugins: [].concat(storyWpConfig.plugins, sanityWpConfig.plugins || []),
github sanity-io / sanity / packages / @sanity / storybook / server / storyConfig / webpack.config.js View on Github external
module.exports = (storyWpConfig, configType) => {
  'use strict' // eslint-disable-line strict

  const sanityWpConfig = sanityServer.getWebpackBaseConfig({
    basePath: process.cwd(),
    commonChunkPlugin: false
  })

  let storybookConf = {}
  try {
    storybookConf = require(path.join(process.cwd(), 'sanity.json')).storybook
  } catch (err) {
    throw err
  }

  sanityWpConfig.module = sanityWpConfig.module || {loaders: []}

  if (configType === 'DEVELOPMENT') {
    sanityWpConfig.module.loaders = sanityServer.applyStaticLoaderFix(sanityWpConfig, {
      listen: Object.assign({
github sanity-io / sanity / packages / @sanity / core / src / actions / start / startAction.js View on Github external
staticPath: resolveStaticPath(workDir, config),
    basePath: workDir,
    httpHost,
    httpPort,
    context,
    project: sanityConfig.get('project')
  }

  checkStudioDependencyVersions(workDir)

  let compileSpinner
  const configSpinner = output.spinner('Checking configuration files...')
  await tryInitializePluginConfigs({workDir, output, env: 'development'})
  configSpinner.succeed()

  const server = getDevServer(serverOptions)
  const compiler = server.locals.compiler

  // "invalid" doesn't mean the bundle is invalid, but that it is *invalidated*,
  // in other words, it's recompiling
  compiler.plugin('invalid', () => {
    output.clear()
    resetSpinner()
  })

  // Start the server and try to create more user-friendly errors if we encounter issues
  try {
    await promisify(server.listen.bind(server))(httpPort, httpHost)
  } catch (err) {
    gracefulDeath(httpHost, config, err)
  }
github sanity-io / sanity / packages / @sanity / storybook / src / config / webpack.config.js View on Github external
function getWebpackConfig(baseConfig, env) {
  /* eslint-disable strict */

  'use strict'

  if (!sanityContext) {
    throw new Error('Sanity context has not been set for Storybook!')
  }

  const wpConfig = Object.assign({}, sanityContext, {commonChunkPlugin: false})
  const sanityWpConfig = sanityServer.getWebpackDevConfig(wpConfig)
  const config = Object.assign({}, genDefaultConfig(baseConfig, env))
  const context = Object.assign({}, sanityContext, {webpack})
  config.plugins = config.plugins.concat(wpIntegration.getPlugins(context))
  config.module.rules = (config.module.rules || []).concat(wpIntegration.getLoaders(context))
  config.module.rules = config.module.rules.filter(skipCssLoader)
  config.module.rules.unshift(sanityWpConfig.module.rules.find(isCssLoader))

  const jsonLoaderAt = config.module.rules.findIndex(rule =>
    (rule.loader || '').includes('json-loader')
  )

  const jsonHackLoader = {
    test: /\.json$/,
    resourceQuery: /sanityPart=/,
    loader: require.resolve('./jsonHackLoader.js')
  }
github sanity-io / sanity / packages / @sanity / cli / src / commands / build / buildCommand.js View on Github external
.then(doc =>
        fsp.writeFile(
          path.join(outputDir, 'index.html'),
          `${ReactDOM.renderToStaticMarkup(doc)}`
        )
      )
github sanity-io / sanity / packages / @sanity / storybook / server / storyConfig / webpack.config.js View on Github external
const sanityWpConfig = sanityServer.getWebpackBaseConfig({
    basePath: process.cwd(),
    commonChunkPlugin: false
  })

  let storybookConf = {}
  try {
    storybookConf = require(path.join(process.cwd(), 'sanity.json')).storybook
  } catch (err) {
    throw err
  }

  sanityWpConfig.module = sanityWpConfig.module || {loaders: []}

  if (configType === 'DEVELOPMENT') {
    sanityWpConfig.module.loaders = sanityServer.applyStaticLoaderFix(sanityWpConfig, {
      listen: Object.assign({
        hostname: 'localhost',
        port: 9001,
        staticPath: './static'
      }, storybookConf)
    })
  }

  return Object.assign({}, sanityWpConfig, storyWpConfig, {
    plugins: [].concat(storyWpConfig.plugins, sanityWpConfig.plugins || []),
    module: Object.assign({}, storyWpConfig.module, sanityWpConfig.module, {
      loaders: [].concat(storyWpConfig.module.loaders, sanityWpConfig.module.loaders)
    })
  })
}
github sanity-io / sanity / packages / @sanity / core / src / actions / build / buildStaticAssets.js View on Github external
await tryInitializePluginConfigs({workDir, output, env: 'production'})

  checkStudioDependencyVersions(workDir)

  const envVars = webpackIntegration.getSanityEnvVars({env: 'production', basePath: workDir})
  const envVarKeys = Object.keys(envVars)
  if (envVarKeys.length > 0) {
    output.print(
      '\nIncluding the following environment variables as part of the JavaScript bundle:'
    )
    envVarKeys.forEach(key => output.print(`- ${key}`))
    output.print('')
  }

  const compiler = getWebpackCompiler(compilationConfig)
  const compile = promisify(compiler.run.bind(compiler))
  let shouldDelete = true

  if (outputDir !== defaultOutputDir && !unattendedMode) {
    shouldDelete = await prompt.single({
      type: 'confirm',
      message: `Do you want to delete the existing directory (${outputDir}) first?`,
      default: true
    })
  }

  let spin

  if (shouldDelete) {
    const deleteStart = Date.now()
    spin = output.spinner('Clearing output folder').start()
github sanity-io / sanity / packages / @sanity / cli / src / commands / build / buildCommand.js View on Github external
handler: ({output, options}) => {
    const outputDir = options._[1] || path.join(options.rootDir, 'dist')
    const config = getConfig(options.rootDir).get('server')
    const compilationConfig = {
      env: 'production',
      staticPath: resolveStaticPath(options.rootDir, config),
      basePath: options.rootDir,
      outputPath: path.join(outputDir, 'static')
    }

    const compiler = getWebpackCompiler(compilationConfig)
    const compile = thenify(compiler.run.bind(compiler))

    const spin = output.spinner('Building Sanity...')
    spin.start()

    const bundle = {}

    return compile()
      .then(statistics => {
        const stats = statistics.toJson()
        if (stats.errors && stats.errors.length > 0) {
          throw new Error(
            `Errors while building:\n\n${stats.errors.join('\n\n')}`
          )
        }