如何让Rollup的内联源图工作?

时间:2018-02-19 17:36:32

标签: express rollupjs

我正在做一个相当奇怪的事情,我在每个请求上表达直接编译Javascript(请假装,目前,这是一个合理的事情;不用说,它仅供内部开发使用)

不幸的是,虽然我尝试了几种配置,但我无法使用源图。

我的快递路线如下:

app.get(`/js/${f.script}`, async (req, res) => {
  try {
    const bundle = await rollup.rollup({
      input: `./examples/src/${f.script}`,
      external: ['React', 'ReactDOM'],
      treeshake: false,
      plugins: [
        resolvePlugin({ jsnext: true, extensions: ['.js', '.jsx'] }),
        commonjsPlugin({ include: 'node_modules/**' }),
        babelPlugin({
          babelrc: false,
          presets: [
            [
              'env',
              { modules: false, targets: { browsers: ['last 2 versions'] } },
            ],
            'react',
          ],
          plugins: ['external-helpers', 'transform-class-properties'],
          exclude: 'node_modules/**',
        }),
      ],
    });

    const { code, map } = await bundle.generate({
      format: 'iife',
      sourcemap: 'inline',
      intro: `var process = {
        env : {
          NODE_ENV : 'development',
        }
      }`,
    });

    res.set('Content-Type', 'text/javascript');
    res.send(
      `${code}\n//@ sourceMappingURL=data:application/json;charset=utf-8,${map}`,
    );
    // eslint-disable-next-line no-console
    console.log(`Served ${f.script}`);
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('oh bad no no', e);
    res.sendStatus(500);
  }
});

这给我一个脚本,然后是:

//@ sourceMappingURL=data:application/json;charset=utf-8,{"version":3,"file":...

它很长,但它看起来像我的相对未经训练的眼睛像源图。浏览器完全忽略它。

我已经尝试了这个,只使用sourcemap: 'inline'而没有其他任何位,它们不会在最后添加源图。我现在已经做了几次手动操作'生成的源映射到脚本的末尾,但Chrome无法识别它。这里是否存在简单的语法错误,或者我的整个方法是错误的?

1 个答案:

答案 0 :(得分:1)

您几乎就在那里 - 您已经确定在使用bundle.generate时需要手动添加评论(如果您使用bundle.write,则会自动为您完成评论相反,但这里没有意义。)

最有可能的是,JSON导致数据URI无效,因此需要将其呈现为base64。附加到map对象的方法可以让您轻松完成此操作:

res.send(
  `${code}\n//# sourceMappingURL=${map.toUrl()}`,
);

可以看到toUrl的实施here

请注意,我使用//#代替//@ - 两者都有效,但//#是正式的首选' (根据spec),//@是遗留工件。