Next.js 和 Webpack 内联 Javascript 或 CSS 资源

Next.js and Webpack inline Javascript or CSS ressources

我有以下用例:我需要使用 React 和 Next.js 生成静态文件。为此,我用以下内容扩展了 next.config.js:

module.exports = {
  exportTrailingSlash: true,
  exportPathMap: async function () {
    const paths = {
      '/': { page: '/' }
    }
    const errorPages = [
      { id: 1, name: '404', lang: 'en' },
      { id: 2, name: '500', lang: 'en' }
    ]

    errorPages.forEach(errorPage => {
      paths[`/errorPage/${errorPage.id}`] = {
        page: '/errorPage/[id]',
        query: { id: errorPage.id }
      }
    })

    return paths
  },
}

这完全有效。在 npm export

之后在 out 文件夹中生成文件

另一个用例是这个: index.html 文件需要在任何地方都能正常工作,而不仅仅是在 out 文件夹中的确切位置。例如,另一个 webapp 查询一个 API,它将 index.html 和 returns 和 html 扫描为该文件中的字符串。这个 html 字符串必须有效,但是 js files/bundles 的引用是相对的(参见 link 和脚本标签):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width,minimum-scale=1,initial-scale=1"
    />
    <meta name="next-head-count" content="2" />
    <link
      rel="preload"
      href="/_next/static/UkokJ2QynwMCza2ya8Vuz/pages/index.js"
      as="script"
    />
    <link
      rel="preload"
      href="/_next/static/UkokJ2QynwMCza2ya8Vuz/pages/_app.js"
      as="script"
    />
    <link
      rel="preload"
      href="/_next/static/runtime/webpack-91b117697e716c22a78b.js"
      as="script"
    />
    <link
      rel="preload"
      href="/_next/static/chunks/framework.94bc9fd9a7de53a90996.js"
      as="script"
    />
    <link
      rel="preload"
      href="/_next/static/chunks/commons.6419ced117edf62014da.js"
      as="script"
    />
    <link
      rel="preload"
      href="/_next/static/runtime/main-2ba45c6c0e61dfa5f796.js"
      as="script"
    />
  </head>
  <body>
    <div id="__next">
      <div style="margin:20px;padding:20px;border:1px solid #DDD">
        <h1>Error Pages</h1>
        <ul>
          <li><a href="/errorPage/1/">test a</a></li>
          <li><a href="/errorPage/2/">test 2</a></li>
        </ul>
      </div>
    </div>    
    <script
      nomodule=""
      src="/_next/static/runtime/polyfills-2889d9d9fcf08314dd3a.js"
    ></script>
    <script
      async=""
      data-next-page="/"
      src="/_next/static/UkokJ2QynwMCza2ya8Vuz/pages/index.js"
    ></script>
    <script
      async=""
      data-next-page="/_app"
      src="/_next/static/UkokJ2QynwMCza2ya8Vuz/pages/_app.js"
    ></script>
    <script
      src="/_next/static/runtime/webpack-91b117697e716c22a78b.js"
      async=""
    ></script>
    <script
      src="/_next/static/chunks/framework.94bc9fd9a7de53a90996.js"
      async=""
    ></script>
    <script
      src="/_next/static/chunks/commons.6419ced117edf62014da.js"
      async=""
    ></script>
    <script
      src="/_next/static/runtime/main-2ba45c6c0e61dfa5f796.js"
      async=""
    ></script>
    <script
      src="/_next/static/UkokJ2QynwMCza2ya8Vuz/_buildManifest.js"
      async=""
    ></script>
  </body>
</html>

有没有办法告诉 next 内联包含这个 js 文件?

我尝试了什么:

我正在尝试使用 HtmlWebpackPlugin and HtmlWebpackInlineSourcePlugin 并像这样更新 next.config.js:

const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin')

module.exports = {
  exportTrailingSlash: true,
  exportPathMap: async function () {
    const paths = {
      '/': { page: '/' }
    }
    const errorPages = [
      { id: 1, name: 404', lang: 'en' },
      { id: 2, name: '500', lang: 'en' }
    ]

    errorPages.forEach(errorPage => {
      paths[`/errorPage/${errorPage.id}`] = {
        page: '/errorPage/[id]',
        query: { id: errorPage.id }
      }
    })

    return paths
  },
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Note: we provide webpack above so you should not `require` it
    // Perform customizations to webpack config
    // Important: return the modified config
    config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
    config.plugins.push(
      new HtmlWebpackPlugin({
        inlineSource: '.(js|css)$' // embed all javascript and css inline
      })
    )
    config.plugins.push(new HtmlWebpackInlineSourcePlugin())
    return config
  }
}

它不会将资源转换为内联格式并保持 linking 它们。有没有办法通过添加任何其他 webpack 来达到预期的结果,或者是配置错误?

提前致谢!

编辑:这是我的 project.json 依赖部分:

"dependencies": {
    "isomorphic-unfetch": "^3.0.0",
    "next": "latest",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "html-webpack-inline-source-plugin": "0.0.10",
    "html-webpack-plugin": "^3.2.0"
  }

我最后做的是使用 StaticDocument 而不是默认的 Document (在生产环境中)。然后我的 StaticDocument 在导出期间与 CustomHead 一起使用。在那里,所有 link 预加载都被删除。这样,最终导出的 HTML 页面的 <head> 中将不会呈现任何 link 标记。

~/pages/_document.js

import Document, { Main, Head } from 'next/document'

class CustomHead extends Head {
  render () {
    const res = super.render()

    function transform (node) {
      // remove all link preloads
      if (
        node &&
        node.type === 'link' &&
        node.props &&
        node.props.rel === 'preload'
      ) {
        return null
      }
      if (node && node.props && node.props.children) {
        return {
          ...node,
          props: {
            ...node.props,
            children: Array.isArray(node.props.children)
              ? node.props.children.map(transform)
              : transform(node.props.children)
          }
        }
      }
      if (Array.isArray(node)) {
        return node.map(transform)
      }

      return node
    }

    return transform(res)
  }
}
   
class StaticDocument extends Document {
  render () {
   return (
      <html>
        <CustomHead />
        <body>
          <Main />
        </body>
      </html>
    )
  }
}

export default process.env.NODE_ENV === 'production'
  ? StaticDocument
  : Document