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

标签 javascript node.js reactjs webpack next.js

我有以下用例:我需要使用 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
  },
}
这完全有效。这些文件正在 out 中生成。 npm export 之后的文件夹
然而,另一个用例是这个:
index.html 文件需要在任何地方都可以工作,而不仅仅是在它在 out 中的确切位置。文件夹。例如,另一个 webapp 查询一个 API,该 API 扫描 index.html 并从该文件中将 html 作为字符串返回。此 html 字符串必须有效,但 js 文件/包的引用是相对的(请参阅链接和脚本标签):
<!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>
有没有办法告诉下一个内联包含这个js文件?
我尝试了什么:
我正在尝试使用 HtmlWebpackPluginHtmlWebpackInlineSourcePlugin并像这样更新了 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
  }
}
它不会将资源转换为内联格式并保持链接它们。有没有办法通过任何其他 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 一起使用导出期间。在那里,所有链接预加载都被删除。像这样,<head> 中不会呈现链接标签。最终导出的 HTML 页面。
~/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

关于javascript - Next.js 和 Webpack 内联 Javascript 或 CSS 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60396928/

相关文章:

node.js - Express 服务器不提供 Index.html 中的静态文件

javascript - React.js 是否以不同方式处理 "static"?复合成分

javascript - 如何声明 proptypes 以验证特定字符串的数组?

javascript - 在 React 中,node.js .getHeaders() 相当于什么? (与axios react 的文件上传)

javascript - 具有多种颜色的 Google 图表网格背景

node.js - 从 mongo shell 连接到 MongoDB 部署时连接尝试失败

android - React-Native 升级到 0.60 后找不到符号

javascript - jquery 在特定动态上获取值 `<td>`

javascript - 调用recordAudio.stopRecording()时套接字连接断开

node.js - 将 csv 文件上传到 Web api 时出现 502 错误