gatsby-remark-prismjs does not highlight when gatsby build

Created on 12 Mar 2018  ·  6Comments  ·  Source: gatsbyjs/gatsby

Description

gatsby-remark-prismjs does not highlight when the site is built using gatsby build

image

But, it works during the development that is (gatsby develop)
image

Steps to reproduce

git clone https://github.com/kkweon/kkweon.github.io.git
yarn
yarn build # that is gatsby build
yarn serve # that is gatsby serve

and check all code highlighting does not work.

However, gatsby develop

yarn develop # that is gatsby develop

will show highlighted codes

Expected result

The code should be highlighted regardless of NODE_ENV

Actual result

No highlighting

Environment

  • Gatsby version (npm list gatsby):

[email protected] /home/kkweon/temp/kkweon.github.io
└── [email protected]

  • gatsby-cli version (gatsby --version):

1.1.45

  • Node.js version: 5.7.1
  • Operating System: Ubuntu 16.04

File contents (if changed):

gatsby-config.js:

const path = require("path");

module.exports = {
  siteMetadata: {
    title: "Mo's Notes",
    siteUrl: "https://kkweon.github.io",
  },
  plugins: [
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-glamor",
    {
      resolve: "gatsby-plugin-typescript",
      options: {
        transpileOnly: false, // default
        compilerOptions: {
          target: "ESNEXT",
          experimentalDecorators: true,
          jsx: `react`,
        }, // default
      },
    },
    {
      resolve: `gatsby-plugin-sitemap`,
    },
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: "UA-69116729-1",
        // Setting this parameter is optional
        anonymize: false,
      },
    },
    {
      resolve: "gatsby-plugin-sass",
      options: {
        precision: 8,
      },
    },
    {
      resolve: "gatsby-plugin-typography",
      options: {
        pathToConfigModule: "src/utils/typography",
      },
    },

    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: path.resolve(__dirname, "src", "posts"),
        name: "blog posts",
      },
    },
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 590,
            },
          },
          "gatsby-remark-copy-linked-files",
          "gatsby-remark-responsive-iframe",
          "gatsby-remark-katex",
          {
            resolve: "gatsby-remark-prismjs",
            options: {
              classPrefix: "language-",
            },
          },
        ],
      },
    },
  ],
};

package.json:

{
  "name": "gatsby-starter-default",
  "description": "Gatsby default starter",
  "version": "1.0.0",
  "author": "Kyle Mathews <[email protected]>",
  "dependencies": {
    "@types/react-helmet": "^5.0.3",
    "font-awesome": "^4.7.0",
    "gatsby": "^1.9.231",
    "gatsby-link": "^1.6.34",
    "gatsby-paginate": "^1.0.12",
    "gatsby-plugin-glamor": "^1.6.11",
    "gatsby-plugin-google-analytics": "^1.0.16",
    "gatsby-plugin-react-helmet": "^2.0.3",
    "gatsby-plugin-sass": "^1.0.16",
    "gatsby-plugin-sitemap": "^1.2.11",
    "gatsby-plugin-typescript": "^1.4.15",
    "gatsby-plugin-typography": "^1.7.12",
    "gatsby-remark-copy-linked-files": "^1.5.25",
    "gatsby-remark-images": "^1.5.41",
    "gatsby-remark-katex": "^1.0.10",
    "gatsby-remark-prismjs": "^1.2.12",
    "gatsby-remark-responsive-iframe": "^1.4.16",
    "gatsby-source-filesystem": "^1.5.15",
    "gatsby-transformer-remark": "^1.7.30",
    "glamorous": "^4.11.4",
    "prismjs": "^1.12.2",
    "react-adsense": "^0.0.4",
    "react-disqus-comments": "^1.1.1",
    "react-helmet": "^5.2.0",
    "typography-theme-bootstrap": "^0.16.7"
  },
  "keywords": [
    "gatsby"
  ],
  "jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "((\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "setupTestFrameworkScriptFile": "<rootDir>/tests/setupEnzyme.ts"
  },
  "license": "MIT",
  "main": "n/a",
  "scripts": {
    "build": "gatsby build",
    "serve": "gatsby serve",
    "develop": "gatsby develop",
    "format": "prettier --trailing-comma es5 --no-semi --single-quote --write \"src/**/*.js\"",
    "clean": "rm -rf public .cache",
    "github": "yarn build && ghp-import -f -p -b master public/",
    "test": "yarn mocha -r ts-node/register -r tests/setupEnzyme.ts tests/**/*.spec.*"
  },
  "devDependencies": {
    "@types/chai": "^4.1.2",
    "@types/enzyme": "^3.1.8",
    "@types/enzyme-adapter-react-15": "^1.0.1",
    "@types/mocha": "^2.2.48",
    "@types/node": "^9.4.4",
    "chai": "^4.1.2",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-15": "^1.0.5",
    "mocha": "^5.0.0",
    "prettier": "^1.10.2",
    "react-test-renderer": "15.6.1",
    "regenerator-runtime": "^0.11.1",
    "ts-node": "^5.0.1"
  }
}

gatsby-node.js:

/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 */

const path = require("path");
const { createFilePath } = require("gatsby-source-filesystem");
const createPaginatedPages = require("gatsby-paginate");

function slugify(text) {
  return text
    .toString()
    .toLowerCase()
    .replace(/\s+/g, "-") // Replace spaces with -
    .replace(/[^\w\-]+/g, "") // Remove all non-word chars
    .replace(/\-\-+/g, "-") // Replace multiple - with single -
    .replace(/^-+/, "") // Trim - from start of text
    .replace(/-+$/, ""); // Trim - from end of text
}

exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
  const { createNodeField } = boundActionCreators;
  if (node.internal.type === "MarkdownRemark") {
    const slug = node.frontmatter.slug || node.frontmatter.title;
    createNodeField({
      node,
      name: "slug",
      value: "posts/" + slugify(slug),
    });
  }
};

exports.createPages = ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators;

  return new Promise((resolve, reject) => {
    graphql(`
      {
        allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
          edges {
            node {
              id
              fields {
                slug
              }
              frontmatter {
                title
                date(formatString: "MMMM DD, YYYY")
              }
              excerpt
            }
          }
        }
      }
    `)
      .then(result => {
        createPaginatedPages({
          edges: result.data.allMarkdownRemark.edges,
          createPage: createPage,
          pageTemplate: "src/templates/Index.tsx",
          pageLength: 5,
          pathPrefix: "",
          context: {},
        });
        result.data.allMarkdownRemark.edges.forEach(({ node }) => {
          createPage({
            path: node.fields.slug,
            component: path.resolve(
              __dirname,
              "src",
              "templates",
              "PostTemplate.tsx",
            ),
            context: {
              slug: node.fields.slug,
            },
          });
        });
        resolve();
      })
      .catch(error => {
        console.error("=====================");
        console.error(error);
        console.error("=====================");
      });
  });
};

gatsby-browser.js:
gatsby-ssr.js:

Most helpful comment

I moved the import from JavaScript to SCSS @import. Now, it works.

Delete the following line.

// src/layouts/index.tsx
import "prismjs/themes/prism-okaidia.css";

Add the following line to main scss file

// main.scss
@import "~prismjs/themes/prism-okaidia";

The problem seems the CSS file is not exported when running at production.
So, I suppose it's something to do with webpack loaders.

All 6 comments

Tracking a potential unrelated cause for this and other issues like it. Can you provide a reproduction repo? I cloned the repo that you used here and everything seems to be working.

Hmm, I already wrote the reproduction step. Any idea why it doesn't work on my computer? I tried different browsers, but no luck.

git clone https://github.com/kkweon/kkweon.github.io.git
yarn
yarn build # that is gatsby build
yarn serve # that is gatsby serve

and open the first post

image

I moved the import from JavaScript to SCSS @import. Now, it works.

Delete the following line.

// src/layouts/index.tsx
import "prismjs/themes/prism-okaidia.css";

Add the following line to main scss file

// main.scss
@import "~prismjs/themes/prism-okaidia";

The problem seems the CSS file is not exported when running at production.
So, I suppose it's something to do with webpack loaders.

Alright - I believe this was addressed in #4495, it's released in [email protected], please confirm and close if fixed.

@erquhart Thank you. I confirmed this issue is solved now.

For anyone else that might land here—I had the same issue, but it was unrelated to the patch above. It turns out gatsby-plugin-purgecss is a little overzealous and deletes the included prism css on build (despite being used). Removing this from your gatsby-config (if that's an option), will solve it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

andykais picture andykais  ·  3Comments

Oppenheimer1 picture Oppenheimer1  ·  3Comments

rossPatton picture rossPatton  ·  3Comments

benstr picture benstr  ·  3Comments

dustinhorton picture dustinhorton  ·  3Comments