Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make extension compatible with Create React App v2.x #2

Closed
satendra02 opened this issue Oct 17, 2018 · 17 comments
Closed

Make extension compatible with Create React App v2.x #2

satendra02 opened this issue Oct 17, 2018 · 17 comments

Comments

@satendra02
Copy link
Owner

satendra02 commented Oct 17, 2018

Error: Cannot find module './polyfills'

After running yarn run eject

@satendra02
Copy link
Owner Author

satendra02 commented Oct 27, 2018

Webpack version is updated in the 2.x version of Create React App.

webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization

Here are the changes you need to do to make it compatible:

  1. Remove require.resolve('./polyfills') dependency from entry key in webpack.config.prod.js file
entry:{
    app: [paths.appIndexJs],
    content: ['./src/content.js']
},
  1. Search for runtimeChunk key in webpack.config.prod.js file and assign it false
runtimeChunk: false,
  1. In your manifest.json file inside public folder add 0.chunk.js file under content_script key
"content_scripts" : [
    {
      "matches": [ "<all_urls>" ],
      "css": ["/static/css/app.css", "/static/css/content.css"],
      "js": ["/static/js/0.chunk.js", "/static/js/content.js"]
    }
 ],

Rest of the implementation is same as mentioned in the blog
https://itnext.io/create-chrome-extension-with-reactjs-using-inject-page-strategy-137650de1f39

@dianasaurio
Copy link

Awesome!! 🎉

@danielgwilson
Copy link

This is spot on but I still found it a bit confusing with create-react-app 2.1.1 ejected. For anyone else slightly confused:

There was no require.resolve(./polyfills) dependency.

Here's my entry in webpack.config.js (which appears to be the only config file now, no webpack.config.prod.js)

entry: {
      app: [
        // Include an alternative client for WebpackDevServer. A client's job is to
        // connect to WebpackDevServer by a socket and get notified about changes.
        // When you save a file, the client will either apply hot updates (in case
        // of CSS changes), or refresh the page (in case of JS changes). When you
        // make a syntax error, this client will display a syntax error overlay.
        // Note: instead of the default WebpackDevServer client, we use a custom one
        // to bring better experience for Create React App users. You can replace
        // the line below with these two lines if you prefer the stock client:
        // require.resolve('webpack-dev-server/client') + '?/',
        // require.resolve('webpack/hot/dev-server'),
        isEnvDevelopment &&
          require.resolve("react-dev-utils/webpackHotDevClient"),
        // Finally, this is your app's code:
        paths.appIndexJs
        // We include the app code last so that if there is a runtime error during
        // initialization, it doesn't blow up the WebpackDevServer client, and
        // changing JS code would still trigger a refresh.
      ].filter(Boolean),
      content: "./src/content.js"
    },

I also had more #.js files in /static/js/ for whatever reason, so here's my extension's entry for content_scripts in the manifest:

"content_scripts": [
    {
      "matches": ["https://google.com/"],
      "css": ["/static/css/app.css", "/static/css/content.css"],
      "js": ["/static/js/0.js", "/static/js/3.js", "/static/js/content.js"],
      "run_at": "document_end"
    }
  ],

@Romstar
Copy link

Romstar commented Aug 24, 2019

I believe this needs to be reopened for the latest version

@satendra02
Copy link
Owner Author

@Romstar Are you facing any kind of issue? Feel free to create a new issue for that with the error logs if you have any.

I have updated webpack version #10 hope it will help.

@Romstar
Copy link

Romstar commented Oct 3, 2019

@satendra02 I have it working now but there were required changes. For example, I don't have to do

    {
      "matches": ["https://google.com/"],
      "css": ["/static/css/app.css", "/static/css/content.css"],
      "js": ["/static/js/0.js", "/static/js/3.js", "/static/js/content.js"],
      "run_at": "document_end"
    }
  ],

I believe I was able to change it to where there is only one output file. I don't recall what I did as this was a month or so ago. When I go through the code again I'll post an update here. Also, there was a webpack change that required some research.

@satendra02
Copy link
Owner Author

@Romstar That's great to hear that you made it work for the latest version of create react app. I believe you are using version 3.x

Please post the changes you did whenever you get time, It will help others if they face the same issue.

You can also create a pull request for the same I will definitely merge it to master

Thanks

@MrGiga
Copy link

MrGiga commented Nov 26, 2019

@danielgwilson These changes result in the following error after running yarn build

Cannot read property 'filter' of undefined

@carlosvq
Copy link

These changes result in the following error after running yarn build

Hi @MrGiga , I had the same problem, to solve that, I did this configuration in my entry point:

    entry: {
      main: [
        // Include an alternative client for WebpackDevServer. A client's job is to
        // connect to WebpackDevServer by a socket and get notified about changes.
        // When you save a file, the client will either apply hot updates (in case
        // of CSS changes), or refresh the page (in case of JS changes). When you
        // make a syntax error, this client will display a syntax error overlay.
        // Note: instead of the default WebpackDevServer client, we use a custom one
        // to bring better experience for Create React App users. You can replace
        // the line below with these two lines if you prefer the stock client:
        // require.resolve('webpack-dev-server/client') + '?/',
        // require.resolve('webpack/hot/dev-server'),
        isEnvDevelopment &&
          require.resolve("react-dev-utils/webpackHotDevClient"),
        // Finally, this is your app's code:
        paths.appIndexJs
        // We include the app code last so that if there is a runtime error during
        // initialization, it doesn't blow up the WebpackDevServer client, and
        // changing JS code would still trigger a refresh.
      ].filter(Boolean),
      content: "./src/content.js"
    },

This problem happened because ManifestPlugin tries to make a filter with the main field.

Screen Shot 2019-11-28 at 11 23 11 AM

To solve this, instead of app, use main to define your main entrypoint on the object as I showed you before.

@chrisstpierre
Copy link

chrisstpierre commented Dec 17, 2019

Here's the list of changes I made for CRA v3.3

    entry: {
      app: [
        isEnvDevelopment &&
          require.resolve('react-dev-utils/webpackHotDevClient'),
        paths.appIndexJs,
      ].filter(Boolean),
      content: paths.appContent,
    },

runtimeChunk: false,
3.
Modify HtmlWebpackPlugin

      new HtmlWebpackPlugin(
        Object.assign(
          {},
          {
            inject: true,
            chunks: ['app'],
            template: paths.appHtml,
            filename: 'popup.html',
          },

Delete

      splitChunks: {
        chunks: 'all',
        name: false,
      },

Change main.filter to app.filter:

          const entrypointFiles = entrypoints.app.filter(
            fileName => !fileName.endsWith('.map'),
          )

@carlosvq
Copy link

carlosvq commented Dec 17, 2019

Hey @chrisstpierre, you can convert it to an object like this:

entry: {
  main: [
    // Include an alternative client for WebpackDevServer. A client's job is to
    // connect to WebpackDevServer by a socket and get notified about changes.
    // When you save a file, the client will either apply hot updates (in case
    // of CSS changes), or refresh the page (in case of JS changes). When you
    // make a syntax error, this client will display a syntax error overlay.
    // Note: instead of the default WebpackDevServer client, we use a custom one
    // to bring better experience for Create React App users. You can replace
    // the line below with these two lines if you prefer the stock client:
    // require.resolve('webpack-dev-server/client') + '?/',
    // require.resolve('webpack/hot/dev-server'),
    isEnvDevelopment &&
      require.resolve("react-dev-utils/webpackHotDevClient"),
    // Finally, this is your app's code:
    paths.appIndexJs
    // We include the app code last so that if there is a runtime error during
    // initialization, it doesn't blow up the WebpackDevServer client, and
    // changing JS code would still trigger a refresh.
  ].filter(Boolean),
  content: "./src/content.js",
  background: "./src/background.js"
},

I hope it helps :-)

@satendra02 satendra02 pinned this issue Dec 17, 2019
@clock-322
Copy link

webpack.config.prod.js file missing after Ejecting create-react-app (npm run eject), my question from where I can set multiple entry points in webpack file.

@satendra02
Copy link
Owner Author

Hi @alphaq1205

check above @danielgwilson answer the file name must be webpack.config.js in the latest version.

@lucaslucenagithub
Copy link

@carlosvq , definitely a solution for the problem, you and @danielgwilson saved my day. Thanks!

@Adrian-Samuel
Copy link

@lucasgit2000 @satendra02 @carlosvq @chrisstpierre

Does anyone have a complete list of changes that they need to make to get this to work with the current ejection of npx create-react-app ejection?

I'm quite new to React and configuring webpack.config.js and matching it correctly to my manifest is quite confusing with the different answers above

@trozler
Copy link

trozler commented Nov 13, 2020

Hi,
I managed to follow the article and get it working with create-react-4.0.0, and I thought this might be of use for someone.

These were the steps I took:

  1. Alter manifest.json from article.
  • Notice we need to include two hashes, these hashes may differ from your project; and chrome will explicitly tell you what hashes to include when you try to load your extension.
  • We also include more js content scripts.
  "content_security_policy": "script-src 'self' 'sha256-NAAKFqXxfjI1LgmKrrc3nxKe0WeY4/Lkue3yXruT4OE=' 'sha256-UtdLJkZdXQ6adZtYaJY8FbnmuNwWtFQ7lkWJX2iMz8E='; object-src 'self'",
  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "css": [
        "/static/css/main.chunk.css",
        "/static/css/content.chunk.css"
      ],
      "js": [
        "/static/js/0.chunk.js",
        "/static/js/5.chunk.js",
        "/static/js/content.chunk.js",
        "/static/js/runtime-content.js"
      ],
      "run_at": "document_end"
    }
  ],
  1. Change webpack.config.js.
    entry: {
      main:
        isEnvDevelopment && !shouldUseReactRefresh
          ? [
              webpackDevClientEntry,
              paths.appIndexJs,
            ]
          : paths.appIndexJs,
      content:
        isEnvDevelopment && !shouldUseReactRefresh
          ? [webpackDevClientEntry, paths.appContentJs]
          : paths.appContentJs,
    },
  • Notice we use main, not app. As pointed out by @carlosvq.

Optional configurations that I think make sense

  • I chose to exclude the content chunk from index.html; as a way of separating the popup view and the content script functionality.
      new HtmlWebpackPlugin(
        Object.assign(
          {},
          {
            inject: true,
            template: paths.appHtml,
            excludeChunks: ["content"],
          },
  • Lastly when debugging my background and content scripts in devtools, I had an issue with loading source maps. I solved this by inlining the source maps; i.e. change "source-map" to "inline-source-map". If you don't want developers to have access to your extension code in production, remember to undo the change.
    devtool: isEnvProduction
      ? shouldUseSourceMap
        ? "inline-source-map"
        : false
      : isEnvDevelopment && "cheap-module-source-map",

Note on cloning template:

I was not able to install the dependencies. I have created an issue #50.
So I instead just followed the article and ran the commands.

Note on create-react-app@4.0.0:

If you are using v4.0.0 there is currently a bug which occurs when you eject. A pull request has been merged, but not been released as of November 13th 2020. So if you want to eject, here is a clean bug fix..
For future versions of create-react-app you should't have to worry about this.

@Adrian-Samuel were you looking for something like this?

@axelmierczuk
Copy link

I was running into an issue with:
entry: { main: isEnvDevelopment && !shouldUseReactRefresh ? [ webpackDevClientEntry, paths.appIndexJs, ] : paths.appIndexJs, content: isEnvDevelopment && !shouldUseReactRefresh ? [webpackDevClientEntry, paths.appContentJs] : paths.appContentJs, },

I needed to add:
appContentJs: resolveModule(resolveApp, "src/content"),
to paths.js under module.exports.
Everything works well with the instructions above.
Hope this helps.

linnerissa added a commit to linnerissa/ChineseReadingHelper-Extension that referenced this issue May 30, 2021
…hich produces a different Webpack file. need to make some modifications according to github.com/satendra02/react-chrome-extension/issues/2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests