Search code examples
node.jstypescriptwebpack-2typescript2.0html-webpack-plugin

webpack multiple output path, limit public access, or custom index.html?


I am using node-express, with typescript.

my folder is setup as follows:

.dist
  public
    public.js
    index.html
  server.js
node_modules
src
  classes
    namespace1
      module1
  public
    app - all angular files. 
    main.ts
  routes
    index.ts
  app.ts
package.json
tsconfig.json
webpack.config.js

Now, I need webpack to output 2 files to /public/public.js and /server.js at .dist folder. nodejs will then run from .dist/server.js, and I want to separate public.js to prevent client to access server.js I also use html-webpack-plugin to generate html files.

I have tried using a little hack like

entry: {
  "server": "./src/app.ts",
  "public/public": "./src/public/main.ts"
}

but then html-webpack-plugin made index.html to load script from /public/public.js instead of public.js

Now, I think we can solve this in 3 way.

  1. Let server.js send public.js using http://localhost/public.js, but it will make managing static folder a little bit complicated. but I will think some way to trick it. Question: how to serve public.js via server.js?
  2. Set entry to "public": "./src/public/main.ts". Question: how to put that public.js into public folder?
  3. Setup html-webpack-plugin to load from /public.js instead of /public/public.js and make index.html inside /public folder. As of now, html-webpack-plugin generates <script type="text/javascript" src="../public/polyfill.js"></script><script type="text/javascript" src="../public/public.js"></script></body> where is should make <script type="text/javascript" src="/polyfill.js"></script><script type="text/javascript" src="/public.js"></script></body> Question: How to do that?

Or is there any other idea to solve this? I am open to any suggestion.

Thank you


Solution

  • I managed by using this config.

    module.exports = [
        {
            entry: "./src/app.ts",
            output: {
                filename: "server.js",
                path: __dirname + "/dist"
            },
            target: "node",
            resolve: {
                extensions: ['.ts', '.js', '.tsx', '.jsx']
            },
            node: {
                __dirname: false
            },
            module: { // all modules here for server
            }
        }, {
            entry: "./src/public/main.ts",
            output: {
                filename: "bundle.js",
                path: __dirname + "/dist/public"
            },
            target: "web",
            plugins: [
                new htmlPlugin({
                    filename: 'index.html'
                })
            ],
            resolve: {
                extensions: ['.ts', '.js', '.tsx', '.jsx']
            },
            module: { // all your modules here. 
            }
        }
    ]