Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Webpack isomorphic loader tools to make Node require handle files like images for Server Side Rendering (SSR)

License

NotificationsYou must be signed in to change notification settings

jchip/isomorphic-loader

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NPM versionBuild StatusDependency StatusdevDependency Status

Webpack Isomorphic Loader

Webpack loader and tools to make node.jsrequire understands files such as images when you are doing server side rendering (SSR).

Purpose

Withwebpack andfile-loader, you can do things like this in your React code:

importsmileyfrom"./images/smiley.jpg";render(){return<div><imgsrc={smiley}/></div>}

That works out nicely, but if you need to do SSR, you will getSyntaxError from node.jsrequire. That's becauserequire only understands JS files.

With this module, you can extendrequire so it understands these files.

It contains three parts:

  1. a webpack loader - to mark asset files
  2. a webpack plugin - collect asset files and generate mapping data
  3. a node.js library - extendrequire for SSR using the mapping data

Install

$ npm install isomorphic-loader --save

Usage

Configuring Webpack

First use the webpack loaderisomorphic-loader to mark all your asset files that you wantextendRequire to handle.

The webpack loaderisomorphic-loader is just a simple pass thru loader to mark your files. It will not do anything to the file content.

Next install the webpack pluginIsomorphicLoaderPlugin to collect and save the list of the marked files.

For example, in the webpack config, to mark the usual image files to be understood byextendRequire:

const{ IsomorphicLoaderPlugin}=require("isomorphic-loader");module.exports={plugins:[newIsomorphicLoaderPlugin()],module:{loaders:[{test:/\.(jpe?g|png|gif|svg)$/i,loader:"file!isomorphic"}]}};

You can also mark any file in your code directly:

importsmileyfrom"file!isomorphic!./images/smiley.jpg";

Extending node.jsrequire

With the marked asset files collected, initializeextendRequire with the mapping data before your server starts:

const{ extendRequire}=require("isomorphic-loader");constisomorphicRequire=extendRequire();// isomorphicRequire is an instance of the ExtendRequire class exported from the module// start your server etc

It will try to load the isomorphic config data fromdist/isomorphic-assets.json. You can also pass in the config data:

extendRequire(options,require("./dist/isomorphic-assets.json"));

Custom Config Overrides

When callingextendRequire, you can pass in a callback inoptions.processConfig to override theisomorphicConfig

extendRequire({processConfig:config=>{// do something with configreturnconfig;}});

Activating and Deactivating extendRequire

  • deactivate API - deactivateextendRequire during run time.
  • activate API - activateextendRequire during run time.
const{ extendRequire}=require("isomorphic-loader");constisomorphicRequire=extendRequire();isomorphicRequire.deactivate();// and reactivate itisomorphicRequire.activate();

Usage with CDN Server

If you publish your assets to a Content Delivery Network server, and if it generates a new unique path for your assets, then you likely have to setpublicPath after webpack compiled your project.

That's whywebpack's document has this note in thesection aboutpublicPath:

Note: In cases when the eventualpublicPath of output files isn't known at compile time, it can be left blank and set dynamically at runtime in the entry point file.If you don't know thepublicPath while compiling you can omit it and set__webpack_public_path__ on your entry point.

In that case, you would have to save the path CDN created for you and pass it toextendRequire with acustom config override, or you can just modify theconfig file directly.

If your CDN server generates an unique URL for every asset file instead of a single base path, then you have to do some custom post processing to update the asset mapping files yourself.

Webpack Dev Server

If you are using webpack dev server, then you probably have two separate processes running:

  1. webpack dev server (WDS)
  2. your app's node.js server (APP)

AndIsomorphicLoaderPlugin would be running inWDS butextendRequire is inAPP.

  • You need to setup some way to transfer the mapping data fromWDS toAPP.
  • When starting up,APP needs to wait for the first mapping data before actually startup, unless your SSR code is not loaded until it's actually invoked.

Here is an example using chokidar to transfer the data through a file:

  • In yourwebpack.config.js:
constfs=require("fs");const{ IsomorphicLoaderPlugin}=require("isomorphic-loader");constisoPlugin=newIsomorphicLoaderPlugin();isoPlugin.on("update",data=>{fs.writeFileSync("./tmp/isomorphic-assets.json",JSON.stringify(data.config));});module.exports={plugins:[isoPlugin]};
  • In your app serverindex.js
const{ extendRequire}=require("isomorphic-loader");// figure out if running in dev mode or notif(process.env.NODE_ENV!=="production"){constchokidar=require("chokidar");constassetFile="./tmp/isomorphic-assets.json";letisomorphicRequire;functionupdateIsomorphicAssets(){constfirstTime=!isomorphicRequire;if(firstTime){isomorphicRequire=extendRequire();}else{// do the necessary require cache refresh so hot module reload works in SSR}isomorphicRequire.loadAssets(assetFile);if(firstTime){startServer();}}constwatcher=chokidar.watch(assetFile,{persistent:true});watcher.on("add",updateIsomorphicAssets);watcher.on("change",updateIsomorphicAssets);// do some timeout checksetTimeout(()=>{if(!isomorphicRequire){console.error("timeout waiting for webpack dev server");}},20000).unref();}else{extendRequire().loadAssets("./dist/isomorphic-assets.json");startServer();}

License

Apache License, Version 2

About

Webpack isomorphic loader tools to make Node require handle files like images for Server Side Rendering (SSR)

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript99.9%
  • CSS0.1%

[8]ページ先頭

©2009-2025 Movatter.jp