当前位置: 首页 > 知识库问答 >
问题:

在rollup/buble中定义全局浏览器

刘英彦
2023-03-14

我正在制作一个Preact SSR应用程序,使用rollup进行捆绑,并使用buble进行ES2015转换。 将当前的客户端代码绑定到其中一个WebSockets中。目前,由于绑定使用的是节点,因此未定义该节点,导致生成错误:

/Users/tim/Documents/Tower/node_modules/@horizon/client/lib/index.js:42


var WebSocketCtor = _ref$WebSocketCtor === undefined ? WebSocket : _ref$WebSocketCtor;
                                                         ^

ReferenceError: WebSocket is not defined
    at Horizon (/Users/tim/Documents/Tower/node_modules/@horizon/client/lib/index.js:42:58)
    at Object.<anonymous> (/Users/tim/Documents/Tower/build/server.js:309:34)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

请记住,我来自Webpack和babel环境。使用这些工具时,我会有一个插件来定义将出现在输出中但不在Node中的内容。如何使用rollup/buble做到这一点?

我当前的生成文件如下所示:

const rollup = require('rollup').rollup
const buble = require('rollup-plugin-buble')
const commonjs = require('rollup-plugin-commonjs')
const json = require('rollup-plugin-json')
const nodeResolve = require('rollup-plugin-node-resolve')
const optimizeJs = require('rollup-plugin-optimize-js')
const replace = require('rollup-plugin-replace')
const uglify = require('rollup-plugin-uglify')
const fs = require('fs-extra-promise')
const sass = require('node-sass').render
const cssnano = require('cssnano').process
const purifycss = require('purify-css')
const { name, dependencies } = require('./package')
const swPrecache = require('sw-precache').write
const nodeRev = require('node-rev').default

const server = () => rollup({
  entry: 'src/server/server.js',
  external: Object.keys(dependencies).concat(['fs']),
  plugins: [
    replace({ '__CLIENT__': false }),
    json(),
    commonjs({ extensions: [ '.js', '.json' ] }),
    buble({ jsx: 'h', objectAssign: 'Object.assign' })
  ]
}).then((bundle) => bundle.write({ sourceMap: true, format: 'cjs', dest: `build/server.js` }))

const client = () => rollup({
  entry: 'src/app/entry.js',
  context: 'window',
  plugins: [
    nodeResolve({ jsnext: true, browser: true }),
    commonjs(),
    replace({ '__CLIENT__': true, 'process.env.NODE_ENV': JSON.stringify('production') }),
    buble({ jsx: 'h', objectAssign: 'Object.assign' }),
    uglify(require('./uglify')),
    optimizeJs()
  ]
})
.then((bundle) => bundle.write({ sourceMap: true, format: 'iife', dest: `build/public/bundle.js` }))

const css = () => new Promise((resolve, reject) => sass({ file: `src/app/styles/entry.scss` }, (err, result) => err ? reject(err) : resolve(result)))
  .then(({ css }) => purifycss(['src/app/components/**/*.js'], css.toString()))
  .then((purified) => cssnano(purified, { autoprefixer: { add: true } }))
  .then(({ css }) => fs.outputFileAsync(`build/public/bundle.css`, css))

const sw = () => swPrecache('build/public/sw.js', {
  cacheId: `${name}`,
  directoryIndex: '/',
  staticFileGlobs: [
    '/',
    './build/public/manifest-*.json',
    // './build/public/bundle-*.{css,js}', // depends if we inlineJs, inlineCss or not
    './build/public/*.{gif,png,svg}' // will not preache /icons
  ],
  navigateFallback: '/',
  dynamicUrlToDependencies: {
    '/': ['./src/server/routes/root.js', './build/public/bundle.css', './build/public/bundle.js', './build/public/manifest.json', './package.json'] // bust cache when these change
  },
  skipWaiting: true,
  stripPrefix: './build/public',
  runtimeCaching: [{
    urlPattern: /\/posts/, // handle remote api call
    handler: 'cacheFirst'
  }]
})

const rev = () => Promise.resolve(nodeRev({
  files: './build/public/**/*.*',
  outputDir: './build/public/',
  file: './build/public/assets.json',
  hash: true  // depends if we inlineJs, inlineCss or not
}))

const clean = () => fs.emptyDirAsync('./build')
const copy = () => fs.copyAsync(`src/app/static/`, `./build/public/`)

const tasks = new Map()
const run = (task) => {
  const start = new Date()
  return tasks.get(task)().then(
    () => console.log('\x1b[36m%s\x1b[0m', '[build]', `'${task}' done in ${new Date().getTime() - start.getTime()}ms`),
    (err) => console.error('\x1b[31m%s\x1b[0m', '[build]', `error running '${task}':`, err.stack)
  )
}

tasks
  .set('clean', clean)
  .set('client', client)
  .set('css', css)
  .set('copy', copy)
  .set('rev', rev)
  .set('server', server)
  .set('sw', sw)
  .set('build', () => run('clean')
    .then(() => Promise.all([run('client'), run('css'), run('copy'), run('server')]))
    .then(() => run('rev'))
    .then(() => run('sw'))
  )

run(/^\w/.test(process.argv[2] || '') ? process.argv[2] : 'build')

共有2个答案

裴宜春
2023-03-14

来自新医生https://rollupjs.org/guide/en/#outputintrooutputoutro只是:

export default {
  ...,
  output: {
    ...,
    intro: 'const ENVIRONMENT = "production";'
  }
};
殷永嘉
2023-03-14

发件人:https://github.com/rollup/rollup/wiki/JavaScript-API#introoutro

intro/outro:类似于banner和footer的字符串,只是代码放在任何特定格式的包装器中

var code = bundle.generate({
  format: 'umd',
  intro: 'var ENVIRONMENT = "production";'
}).code;
 类似资料:
  • A-Frame通过window.AFRAME浏览器全局变量来暴露其公共接口。 (require('aframe')). AFRAME属性 属性(Property) 描述 AComponent 组件(Component)原型。 AEntity 实体(Entity)原型。 ANode A-Frame元素继承的基础节点原型。 AScene 场景(Scene)原型。 components 已注册的组件对象

  • 本文向大家介绍Android自定义 WebView浏览器,包括了Android自定义 WebView浏览器的使用技巧和注意事项,需要的朋友参考一下 WebView是Android中一个非常实用的组件,它和Safai、Chrome一样都是基于Webkit网页渲染引擎,可以通过加载HTML数据的方式便捷地展现软件的界面。 在布局文件中添加<EditText/>和<Button/>控件, 在布局文件中添

  • 在Angular 1. x中,您可以这样定义常量: Angular(使用TypeScript)中的等价物是什么? 我只是不想在我的所有服务中一遍又一遍地重复API基url。

  • 浏览保护 启动安全浏览后,在允许内容开始加载前,所有的URL都会被检查。URL通过两个列表进行检查:恶意软件和钓鱼网站。根据匹配到的列表,我们会在一个中转页面显示不同的警告页面。 检查安全浏览数据库是一个多步骤的过程。 URL首先会被哈希,然后会用内存中前缀列表进行同步的检查。 如果前缀得到匹配,会向安全浏览服务器发起一个异步请求,拉取这个前缀的全量哈希列表。 一旦这个列表返回,完整的哈希会与列表

  • 问题内容: 是否可以在JavaScript函数中定义全局变量? 我想在其他函数中使用变量(在函数中声明)。 问题答案: 是的,正如其他人所说的,您可以在全局范围内(在所有函数之外)使用声明全局变量: 或者,您可以在上分配一个属性: …因为在浏览器中,用声明的 所有全局变量 都是对象的属性。(在最新规范ECMAScript 2015中,全局范围内的new ,和语句创建的不是全局对象属性的全局变量;这

  • 问题内容: 在Coffeescript.org上: 将编译为: 通过在node.js下的coffee-script进行编译可以做到: 文件说: 如果要创建供其他脚本使用的顶级变量,请将它们作为属性附加到窗口或CommonJS中的exports对象上。如果您同时针对CommonJS和浏览器,那么存在运算符(见下文)为您提供了一种可靠的方法来确定将它们添加到何处:root = exports?这个 然