GithubHelp home page GithubHelp logo

bundle-loader's People

Contributors

andreirailean avatar cap-bernardito avatar fernandoacorreia avatar gaearon avatar joshwiens avatar kevinzwhuang avatar michael-ciniawsky avatar mobiushorizons avatar nickdima avatar noscripter avatar pavlodeshko avatar shama avatar simon04 avatar sokra avatar spacek33z avatar statianzo avatar tobenna avatar zxcabs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bundle-loader's Issues

Loading JSON files with bundle-loader crashes

Hello,

I'm not sure what I'm doing wrong but for some reason, if I try to lazily load JSON files using this loader, webpack interprets the generated loading code as if it were JSON too and tries to parse it.

This happens using Webpack 4.1.1

I assume it's because the name of the resource bundle-loader generates ends with .json too. (eg. ./node_modules/bundle-loader?lazy&name=file-[name]!./json-files/a.json)

I reproduced the issue using only bundle-loader and a couple of JSON files here: http://github.com/Ephys/bundle-loader-bug

Here is the webpack log of the above project: https://github.com/Ephys/bundle-loader-bug/blob/master/stacktrace.log

Thank you in advance for your help! :)

Does not support require.ensure error callback added in Webpack 2.4

Webpack 2.4 added support for error callbacks as a 2nd argument to require.ensure:

webpack/webpack#4069

This is not supported by the bundle-loader, but there is a forked version of the loader that does support the require.ensure error callback: https://github.com/jharris4/split-chunk-loader

I'd consider making a PR to merge the changes from split-chunk-loader into bundle-loader, but not sure of the best way to handle the fact that webpack >= 2.4 is required for that to work. Maybe adding a peerDependency would do the trick?

Global override `lazy` in test environment to prevent chunking

I'm using lazy loading for code splitting with great success!

import Dashboard from 'bundle?lazy!./components/Dashboard'

The problem comes during testing:

WARNING in ./~/bundle-loader?lazy!./src/routes/Home/components/Dashboard.js
There is another module with an equal name when case is ignored.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Rename module if multiple modules are expected or use equal casing if one module is expected.

If it's a test environment, I'd like to be able to globally disable lazy loading. Due to the nature of static ES6 imports, I cannot parameterize the import.

Is this something that would seem useful as a PR?

Are there other ways of solving this (while leaving my import as-is.)? NOTE: I don't want to configure an implicit bundle-loader based on path, I want the explicit import.

When server-side rendering, it doesn't load anything

Doing something like this for react-router:

import loadFAQ from 'bundle-loader?lazy!components/pages/faq'

const FAQ = () => (
  <Bundle load={loadFAQ}>
    {(FAQ) => FAQ ? <FAQ /> : null}
  </Bundle>
)

const Pages = () => (
  <SiteLayout>
    <Switch>
      <Route path="/faq" component={FAQ} />
    </Switch>
  </SiteLayout>
)

export default Pages

For some reason, it's not loading from the server. Removing ?lazy doesn't make it work either. I understand this is loading async, but is there some way to know if the environment is Node and set it to sync vs async when client-side rendered? Is there something I can pass in the Webpack config depending on if it's the server or client build?

Breaks in Webpack 4 with `name` option

Using bundle-loader and specifying a name throws an error in Webpack 4.

import other from 'bundle-loader?lazy&name=myChunk!./other';

fails compilation with the error

ERROR in ./node_modules/bundle-loader?lazy&name=myChunk!./src/other.js

Module build failed: TypeError: Cannot read property 'context' of undefined

    at Object.module.exports.pitch (/app/node_modules/bundle-loader/index.js:13:43)

@ ./src/index.js 1:0-60 3:0-5

It appears that Webpack 4 is not setting this.options when invoking loader functions. From bundle-loader source:

var options = {
  context: query.context || this.options.context, // <-- Cannot read property 'context' of undefined
  regExp: query.regExp
};

I'd be glad to make a PR to fix this, but I'm not sure if the problem is a Webpack 4 issue or bundle-loader. If it's bundle-loader's issue, what's the desired behavior?

Versions

Webpack: 4.0.0-beta.0
bundle-loader: 0.5.5

Example

Glitch.me project that reproduces the error

Lazily loads bundle multiple times

I'm not sure if this is expected, but I'm basically doing something like:

let loader = require('bundle?lazy&name=my-chunk!./file.js');

function doSomething() {
  loader(exportedObj => ...do stuff..)
}

I assumed that the first time I called doSomething, it would fetch the bundle, and subsequent calls would used the previously fetched bundle, but it appears a new script tag is placed in each time.

Is this expected?

Require from server

How to require this loader server side?
I tried var app = require('bundle?lazy!./app') and I got error that module 'bundle?lazy!./app' not found.

emoji table

Hello,

This plugin is great at its job, unfortunately it requires loader-utils which requires emojis-list so I was somehow surprised that this plugin added the whole emoji table in my JS code as a dependency. Is there any way to prevent this apart from forking your repository and deleting the loader-utils dependency?

Regards,

Not lazy loading as expected

My code
var $ = require('bundle?lazy&name=chunk.jquery!jquery');

It puts the jquery in theapp.bundle. But I want jquery to be a separate chunk which is lazy loaded only in the component that requires it. Why is it going into app.bundle and loading for all pages?

Just trying to get async jquery load.

how to merge chunks in one page

In a react app, I want to dynamically load reducer and indexComponent.
bundle-loader will build two chunks.
How to merge reducer chunk and component chunk in one chunk.

Is it possible to use with modules of node_modules?

Is it possible to use with modules of node_modules?

When using this i receive TypeError: cb is not a function

My code is:
import Display from 'bundle-loader?lazy!../../node_modules/<module>/widgets/Display/Display.component.jsx';

Unclear documentation

I've reached this loader from webpack official page. It was mentioned as an example of loaders using pitch function. The idea of pitch function is clear but I can't understand the purpose of this loader. Can I simply use require.ensure instead of it? Would you please improve readme or just explain me an idea and I'll make a PR myself.

Error with json loader

Install cldr-data and json-loader

npm install cldr-data json-loader

Add this to the config:

{ test: /\.json$/, loader: "json" },

And then try this:

require([
    'bundle?name=[path]!cldr-data/main/' + locale + '/numbers.json',
    'bundle?name=[path]!cldr-data/main/' + locale + '/ca-gregorian.json',
    'bundle?name=[path]!cldr-data/main/' + locale + '/timeZoneNames.json'
], function(a, b, c) {
});

This combines all the jsons in one locale directory into a single chunk, which is good. Unfortunately, the chunk looks like this:

webpackJsonp([150],{

/***/ 394:
/***/ function(module, exports) {

    module.exports = {

And I get the following error:

Uncaught json: E_INVALID_PAR_TYPE: {"expected":"Plain Object","name":"json"}

webpack-defaults upgrade

Addition of webpack-defaults & associated refactoring as a part of the next Major release

Issue exists for status tracking across the organization.

Please do not close

bundle-loader 404

in react-router-dom,code split,url path (pushState),webpack load bundle by the path relative to new path,but the bundle file in root path?

how resolve?

bundle-loader is outdated for webpack2 & 3?

I am looking for a way to handle the loading error.
import() and require.ensure() allow handling the loading error.
But bundle-loader seems do not support this?

From the source code, its implemetation is based on require.ensure() .

https://github.com/webpack-contrib/bundle-loader/blob/master/index.js

I think bundle-loader is outdated for webpack2 & 3.

Because with webpack 2 & 3, require.ensure() parameters is changed.

Here is the latest version (webpack 3.10.0):
require.ensure(dependencies: String[], callback: function(require), errorCallback: function(error), chunkName: String)

bundle-loader does not handle the errorCallback, and, the third parameter is not chunkName.

Am I correct?

a warning and a problem

warning as below:
image
an a problem is that when I start a fetch in React component's lifecycle, this fetch never ends.

The trouble of 'require("bundle-loader?lazy&name=my-chunk!./file.js");'

If I use the code below , it won't work ! It is just like that I didn't use bundle-loader.

import file from "bundle-loader?lazy&name=my-chunk!./file.js";

But if I modify my code below ,it work !

import file from "bundle-loader?lazy&name=my-chunk-[name]!./file.js";

The webpack.config.js in my project is:

output: {
        path: path.resolve(__dirname, './output'),
        filename: '[name].[chunkhash:8].bundle.js',
        chunkFilename: '[name]-[id].[chunkhash:8].bundle.js',
    },

BTW:The version I used is react^15.4.2 & react-router-dom^4.0.0 & bundle-loader^6.4.1

How do you use it in practice?

I mean, it changes syntax. It changes default behavior.
Async require works and expected to work like this:

require(["./foo.js"], function(fileExports) {
  // use it
});

But now we can't do this. Now we should do some magic:

require(["./foo.js"], function(cb) {
    cb(function(fileExports) {
       // use it
    });
}

Besides it already violates basic principles, webpack documentation says that loaders should be mostly defined in webpack config. Which is reasonable. And when we define our bundles in config, then in code we have no idea about what this module exactly is - and so which syntax must be used to actually load it. Sure, it can have some self-describing name, but it's not a real solution.

Can't understand how to practically use it. Should I really write require("bundle!...") everywhere?

react-router4, bundler-loader and typescript problem

when i use typescript
i set webpack module loaders
{ test : /\.tsx?$/, include: path.resolve(__dirname, './src/router/'), loaders : ['bundle-loader?lazy', 'babel-loader','ts-loader'] }
and it will show me the error 'props.load is not a function';

App.tsx
`import 'babel-polyfill';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {
HashRouter,
Route
} from 'react-router-dom';

import Bundle from './bundle';

import HomeIndex from './router/homes/home';

const Home = () => (

{
(Home : any) =>
}

);

ReactDOM.render(


welcome to react





,document.getElementById('root')
);

`

Bundle.tsx
`import * as React from 'react';
export default class Bundle extends React.Component< any,any > {
constructor( props?:any ) {
super(props);
this.state = {
mod : null
}
}

componentWillMount() {
    this.load(this.props)
}

componentWillReceiveProps( nextProps : any ) {
    if (nextProps.load !== this.props.load) {
        this.load(nextProps)
    }
}

load( props:any) {
    this.setState({
        mod: null
    });
    props.load(( mod :any ) => {
        this.setState({
            mod: mod.default ? mod.default : mod
        });
    });
}

render() {
    return this.state.mod ? this.props.children(this.state.mod) : null;
}

}`

[documentation] FLow

Hello,

To use bundle-loader with Flow, you have to put into .flowconfig this option :

module.name_mapper='^bundle-loader\?lazy!\(.*\)$' -> '\1'

Hope this will help

Why the chunck cannot load while I am browser local run resource which webpack builded with bundle-loader

Question: Can bundle-loader support local browser to load the chunk?

  1. I am using webpack and bundle-loader to build my app. And home.js will be use in app.js
import loadHome from 'bundle-loader?lazy!../src/pages/Home';
  1. After build, I am access my app with localhost:8080 in local server(http-server).
  2. But I found that when I just drag the index.html to open in chrome browser, It cannot load the chunck(home.js) which use bundle-loader to build. You can see that I already load app.js, but app.js should load the home.js! But actually, it just load the app.js without loading home.js. And I cannot get any error or warning in chrome console panel!
    capture

[Question] Usage with webpack 2 - dynamic import

Hey guys,

I'm a bit puzzled regarding the usage of this plugin with the "new" dynamic import implementation of webpack@2.

In our project we are using this plugin. Now that we are upgrading to webpack@2, should we keep using this plugin or is the preferred way now to use import? I couldn't find any mention about this in the documentation.

Thanks a lot

dynamic chunk name support?

here is my code:

function loadModules(names) {
	names.forEach(function(name) {
		require("bundle!./modules/" + name + ".js")(function(module) {
			console.log(module);
		});
	})
}

webpack output:

Hash: 63772999c38e15403ad6
Version: webpack 1.13.1
Time: 451ms
                       Asset       Size  Chunks             Chunk Names
main.63772999c38e15403ad6.js    8.74 kB       0  [emitted]  main
               chunks/1.1.js  203 bytes       1  [emitted]
               chunks/2.2.js  203 bytes       2  [emitted]
               chunks/3.3.js  203 bytes       3  [emitted]
                  index.html  333 bytes          [emitted]
   [0] ./src/main.js 2.15 kB {0} [built]
   [3] ./src/modules/a.js 29 bytes {1} [built]
   [5] ./src/modules/b.js 29 bytes {2} [built]
   [7] ./src/modules/c.js 29 bytes {3} [built]
    + 4 hidden modules
Child html-webpack-plugin for "index.html":
        + 3 hidden modules

But the chunk filename is 1.1.js, 2.2.js, 3.3.js. I want to get the module filename like:
[id].[name].js.

But when I modify my code like this:

function loadModules(names) {
	names.forEach(function(name) {
		require("bundle?name=" +name+ "!./modules/" + name + ".js")(function(module) {
			console.log(module);
		});
	})
}

webpack output:

Hash: ddb1bfed1d512f444e7d
Version: webpack 1.13.1
Time: 453ms
                       Asset       Size  Chunks             Chunk Names
main.ddb1bfed1d512f444e7d.js    4.19 kB       0  [emitted]  main
                  index.html  333 bytes          [emitted]
   [0] ./src/main.js 2.16 kB {0} [built]
   [1] ./src ^bundle\?name=.*\.js$ 160 bytes {0} [built]
Child html-webpack-plugin for "index.html":
        + 3 hidden modules

bundle-loader not work. It does not generate my module chunks.

[Docs] [Question] improvements for react-lazy-load

Hello,

There is a tip in this page: https://webpack.js.org/guides/lazy-load-react/ that says:

By using the bundle loader we can semantically name chunks to intelligently load groups of code.

  • What does it mean? what is the expected output from this?
  • Could someone write an actual "how-to" on the docs page?

There are a few plugins that are related to split / bundle / lazyload. The path to the right solution is not clear for me.

Especially on another page about migrating to webpack2, it is said:

Caveat: require.ensure allows for easy chunk naming with the optional third argument, but import API doesn't offer that capability yet. If you want to keep that functionality, you can continue using require.ensure.

Does that mean that it's possible to name bundles with bundle-loader in some way, although supposedly not possible by using Webpack import?

Bundle load error callback?

Hello, I've developing an async application and I am getting some problems with deploys and hash.chunks while the user is interacting in the website, I tough was possible to get error callback in loaders, but I didn't figure out. Is it possible to create this feature?

var load = require("bundle?lazy!./file.js");
load(function(file) {

}, function(err){

});

Using Mocha Test

I am using the loader syntax in a require statement. Everything is working fine, until I go to execute or mocha test. At that point I am getting the following error. Does anyone know how to get around the error?

Error: Cannot find module 'bundle-loader!./index'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:/Development/Workspaces/.../file.js:21:11)
    at Module._compile (module.js:570:32)
    ...

webpack 4 bundle compress bug

compress and uglify is not working on webpack 4 (works fine on webpack 3)

webpack config

output: {
            path: path.join(__dirname, 'public/bundles/'),
            filename: '[name].js',
            chunkFilename: 'modules/[name]-[hash].js',
            publicPath: 'http://.........com'
        },
   optimization: {
            minimize: true,
            splitChunks: false
        },
 plugins: [
            new webpack.DefinePlugin({
                'process.env': Object.assign({
                    'NODE_ENV': JSON.stringify('production'),
                   ....
                }, bundle.bundleModel)
            }),
            new webpack.DllReferencePlugin({
                context: path.join(__dirname, 'public/vendor/'),
                manifest: manifest
            }),
            new webpack.LoaderOptionsPlugin({
                minimize: true
            }),
            new UglifyJsPlugin({
                sourceMap: false
            }),
            new webpack.optimize.AggressiveMergingPlugin({
                moveToParents: true
            }),
            new webpack.optimize.ModuleConcatenationPlugin(),
        ]

import

import SoccerCommentary from 'bundle-loader?lazy&name=[name]!../../commentary/soccer/soccer-commentary';

screen shot 2018-03-05 at 2 39 48 pm

Why webpack throw an warning when I use require.ensure and require.context?

//Warning! not work
const loadComponentWithContext = (moduleName) => {
	return (nextState, cb) => {
		require.ensure([], require => {
			var reqWithCtx = require.context(`./modules/${moduleName}`, true, /\.js$/);
			var component = reqWithCtx('/index.js').default;
			console.log(component);
			cb(null, component);
		}, moduleName)
	}
};

//worked, each module is a chunk
const loadComponentWithBundleLoader = (moduleName) =>  (nextState, cb) => {
    require('bundle-loader!./modules/'+ moduleName + '/index.js')(function(module) {
        cb(null, module.default);
    });
}

//worked, but only one chunk
const loadComponent = (moduleName) => (nextState, cb) => {
	require.ensure([], require => {
		var es6Component = require(`./modules/${moduleName}/index.js`);
		cb(null, es6Component.default);
	})
}

const routes = (
	<Route path='/'>
		<IndexRoute getComponent={loadComponent('home')}></IndexRoute>
		<Route path='about' getComponent={loadComponent('about')}></Route>
		<Route path='contact' getComponent={loadComponent('contact')}></Route>
	</Route>
);

loadComponentWithContext throw an warning:

WARNING in ./src/route.js
Critical dependencies:
46:2-9 require function is used in a way in which dependencies cannot be statically extracted
 @ ./src/route.js 46:2-9

WARNING in ./src/index.html
Module parse failed: /Users/dulin/workspace/webpack-summer/bundle-loader/react-demo-1/src/index.html Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:0)
    at Parser.pp.raise (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:920:13)
    at Parser.pp.unexpected (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:1483:8)
    at Parser.pp.parseExprAtom (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:330:12)
    at Parser.pp.parseExprSubscripts (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:225:19)
    at Parser.pp.parseMaybeUnary (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:204:17)
    at Parser.pp.parseExprOps (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:151:19)
    at Parser.pp.parseMaybeConditional (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:133:19)
    at Parser.pp.parseMaybeAssign (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:110:19)
    at Parser.pp.parseExpression (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:86:19)
    at Parser.pp.parseStatement (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:1753:23)
    at Parser.pp.parseTopLevel (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:1648:21)
    at Parser.parse (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:1616:17)
    at Object.parse (/usr/local/lib/node_modules/webpack/node_modules/acorn/dist/acorn.js:882:44)
    at Parser.parse (/usr/local/lib/node_modules/webpack/lib/Parser.js:902:15)
    at DependenciesBlock.<anonymous> (/usr/local/lib/node_modules/webpack/lib/NormalModule.js:104:16)
    at DependenciesBlock.onModuleBuild (/usr/local/lib/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
 @ ./src ^\.\/.*$

WARNING in ./src ^\.\/.*$
Module not found: Error: a dependency to an entry point is not allowed
 @ ./src ^\.\/.*$

WARNING in ./src ^\.\/.*$
Module not found: Error: a dependency to an entry point is not allowed
 @ ./src ^\.\/.*$

I saw the source code of bundle-loader, it wrap require.ensure.
How do I make loadComponent worked like bundle-loader?

Named chunks

@sokra as per our discussion here I'm working on implementing the name parameter.
I think it should work for both regular and dynamic requires. For dynamic requires it should be a regex that extracts the name from the filename being processed. A few questions:

  • should I use the same name parameter for both and detect in some way if it's a plain string or regular expresion? or better to use different parameters? Any examples of loaders that use regex in the query?
  • is it safe to suppose that the filename is always the last part of remainingRequest?

Unable to load CSS properly

I'm setting up a simple code splitting with Webpack 2, React Router 4 and bundle-loader:

It's working very well, for the JavaScript part, but for some weird reason, it's not loading the CSS Modules (which are inside the Home component that's being lazy loaded).

This is what should happen:

This is what is happening:

Here's the code:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';

class Routes extends Component {
  constructor(props) {
    super(props);

    this.state = {
      home: null,
    };
  }

  componentDidMount() {
    const waitForChunk = require('bundle-loader?lazy!../home/Home');
    waitForChunk(file => {
      this.setState({ home: file.default });
    });
  }

  render() {
    return (
      <Router>
        <div>
          <Route exact path="/" component={this.state.home} />
        </div>
      </Router>
    );
  }
}

export default Routes;

and here's the webpack config:

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

const host = process.env.HOST || '0.0.0.0';
const port = process.env.PORT || 4000;
const buildDirectory = path.join(__dirname, './build');

const stats = {
  assets: true,
  children: false,
  chunks: false,
  hash: false,
  modules: false,
  publicPath: false,
  timings: true,
  version: false,
  warnings: true,
  colors: {
    green: '\u001b[32m',
  },
};

module.exports = env => {
  const nodeEnv = env && env.prod ? 'production' : 'development';
  const isProd = nodeEnv === 'production';

  const plugins = [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(nodeEnv),
      },
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'index.html'),
      filename: 'index.html',
      inject: true,
      production: isProd,
      minify: isProd && {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.optimize.CommonsChunkPlugin({
      async: true,
      children: true,
      minChunks: 2,
    }),
    new ExtractTextPlugin('style-[contenthash:8].css'),
    new ScriptExtHtmlWebpackPlugin({
      defaultAttribute: 'async',
    }),
    new PreloadWebpackPlugin(),
  ];

  if (isProd) {
    plugins.push(
      new UglifyJSPlugin({
        compress: {
          warnings: false,
          screw_ie8: true,
          conditionals: true,
          unused: true,
          comparisons: true,
          sequences: true,
          dead_code: true,
          evaluate: true,
          if_return: true,
          join_vars: true,
        },
      }),
      new OfflinePlugin()
    );
  }

  return {
    devServer: {
      inline: true,
      host,
      port,
      historyApiFallback: true,
      overlay: {
        errors: true,
        warnings: true,
      },
    },
    resolve: {
      alias: {
        react: isProd ? 'preact-compat' : 'react',
        'react-dom': isProd ? 'preact-compat' : 'react-dom',
      },
    },
    devtool: isProd ? 'source-map' : 'cheap-module-source-map',
    entry: './src/index.js',
    output: {
      path: buildDirectory,
      publicPath: '/',
      filename: '[name]-[hash:8].js',
      chunkFilename: '[name]-[chunkhash:8].js',
    },
    performance: isProd && {
      maxAssetSize: 500000,
      maxEntrypointSize: 500000,
      hints: 'warning',
    },
    stats,
    module: {
      rules: [
        {
          test: /\.(js)$/,
          exclude: /node_modules/,
          use: ['babel-loader'],
        },
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            loader: 'css-loader',
          }),
        },
        {
          test: /\.scss$/,
          loader: ExtractTextPlugin.extract({
            loader: 'css-loader',
            options: {
              modules: true,
              importLoaders: 2,
              localIdentName: '[hash:base64:5]',
            },
          }),
        },
        {
          test: /.(mp4|png|jpg|woff(2)??|eot|otf|ttf|svg)(\?[a-z0-9=\.]+)?$/,
          use: ['file-loader?limit=100000'],
        },
      ],
    },
    plugins,
  };
};

Error since 0.5.4

2a25922

@sokra this change somewhat break the logic,
previously we have two config like

  1. /a/b/node_modules/a/b/file.js
  2. /a/b/file.js
    seems like the context will also change based on the caller as well,
    so those two file generate the same relative path after the stringifyRequest logic in the utils

so those two config all output as
./file.js
which break the previous logic

Advantages/disadvantages over import()

I’d like to document how this solution is different from import()/require.ensure(). This would simplify the choice between these tools: from the first sight, bundle-loader?lazy and import() are very similar, and you could get stuck thinking what to choose.

This is what I’ve found so far:

  • Advantage: Per react-router docs, on additional renders, the loader calls the callback synchronously. This prevent the flashing of the loading screen.
  • Disadvantage: import() and require.ensure() allow handling the loading error (e.g. with .catch()), and bundle-loader doesn’t.
  • Disadvantage: Because this is a loader, the developer should either
    • name a file after a specific pattern (e.g. .lazy.js) to apply the loader to it (this requires renaming files, which is a pretty large event) or
    • specify the loader inline (which is a rare and webpack-specific notation).

Are there any other known differences I’m missing?

named export is `undefined`

When using loader's syntax I get undefined for named exports:

// Comey.js
const Dismissed = () => <div> :| </div>
const Career = () => <div> ;| </div>

export {
  Dismissed as default,
  Career
};


// main.js
import Dismissed, { Career } from 'bundle-loader?lazy!./Comey';

console.log(Dismissed); //  function (cb) { blah }
console.log(Career);  // `undefined`


// - "webpack":       "2.4.1",
// - "bundle-loader": "0.5.5",

bundle not found

I installed bundle-loader from npm and it says it's not found. I've verified the package is in my node_modules dir. I'm installing version 0.5.1.

var PreDashboard = React.createClass({
  mixins: [AsyncReactComponent],
  bundle: require('bundle?lazy!./Dashboard.react.js'),
  preRender: function() {
    return <div>Loading dashboard...</div>
  }
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.