简体   繁体   中英

How do I insert Webpack-generated code into a server-side node.js script?

I have a web-application written in Typescript. No frameworks because they don't suit my tasks. The app is compiled with Webpack. So far it works fine. Then I wanted to implement server-side rendering of some parts of the app. I want some parts of my code and my html-pages along with images and styles be served by a node.js script.

So. I am trying to configure Webpack to make me a js-file that I could then require into my another ssr.js node.js server script. But I don't know how to do it. The resulting script is wrapped into something and it stumbles upon window not being defined and not being equal to global namespace.

How do I approach the task? Is Webpack in general suitable for compiling server-side scripts? If not then how else do I go about server-side rendering?

My .ts file are process with the ts-loader :

{
   test: /\.ts$/,
   use: 'ts-loader',
},

Update: I added target: 'node' as proposed in another question but it isn't enough in general. The errors with window are gone but now I can't connect what I export with what I require ;

My file looks like this:

export function someFunc(x) {
    // Some code
}

I expect that I can do

const something = require('somefile');

and the fetch my someFunc from within sonething . But this does not work. In place of something I get a strange object that looks like this:

{ ids: [ 0 ],
  modules: 
   [ [Function],
     [Function],
     [Function],
     [Function] ]
}

Ok, I had two problems. One was already answered, I had to set Webpack's target to node . Now I found what was the second issue. It was CommonsChunkPlugin . This plugin is not compatible with taget: 'node' . I had to remove it for server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM