Making a node_module global using Webpack 2 - javascript

I am using the below package on an angular project:
https://github.com/pablojim/highcharts-ng
A requirement is that it needs highcharts as a global dependency, in which it tells you to add a script tag into your html:
<script src="http://code.highcharts.com/highcharts.src.js"></script>
Rather than add the above script tag into my HTML I would like to make it global via Webpack.
I have installed highcharts via npm and have tried using the ProvidePlugin and the noParse methods described here (to no avail): https://webpack.js.org/guides/shimming/#scripts-loader
For the ProvidePlugin option I used:
new webpack.ProvidePlugin({
Highcharts: "highcharts",
})
for noParse:
noParse: [
/[\/\\]node_modules[\/\\]highcharts[\/\\]highcharts\.js$/,
],
Neither worked, meaning when highcharts-ng tried to work, it gets an error because it cannot create a new Highcharts:
TypeError: Cannot read property 'Chart' of undefined
// from highcharts-ng which throws above error
chart = new Highcharts[chartType](mergedOptions, func);
Here is my angular module
import angular from 'angular'
import highchartsNg from 'highcharts-ng'
import { ReportsData } from './reports.data'
import { reportsWidget } from './reports-widget/component'
export const ReportsModule = angular
.module('reports', [
highchartsNg,
])
.factory('ReportsData', ReportsData)
.component('reportsWidget', reportsWidget)
.name
My webpack config:
var webpack = require('webpack')
module.exports = {
context: __dirname + '/app/modules',
entry: {
vendor: ['angular', 'highcharts-ng'],
modules: './modules.js',
},
output: {
path: __dirname + '/.tmp/modules',
filename: '[name].bundle.js',
},
plugins: [
// info: https://webpack.js.org/guides/code-splitting-libraries/
new webpack.optimize.CommonsChunkPlugin({
name: ['vendor', 'manifest'],
}),
],
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: { presets: ['es2015'] },
},
],
},
],
},
}

Use expose-loader and write require('expose-loader?Highcharts!highcharts'); somewhere before the first usage of Highcharts global variable. This will require highcharts and save expose it as window.Highcharts in the browser.
Under the hood webpack makes it available for you as:
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {module.exports = global["Highcharts"] = __webpack_require__(1);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))
/***/ }

Related

How to import jquery in webpack

I have a problem with jquery when i using it on webpack.
My code:
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
entry: {
vendor: [
'./src/main/webapp/js/vendor/jquery-3.3.1.min.js',
// './src/main/webapp/js/vendor/fs.js',
'./src/main/webapp/js/vendor/google-adsense.js',
'./src/main/webapp/js/vendor/jquery.menu-aim.min.js',
'./src/main/webapp/js/vendor/jquery.touchSwipe.min.js',
],
app: './src/main/assets/js/desktop/app.js',
mobile: './src/main/assets/js/mobile/app.js',
touch: './src/main/assets/js/touch/app.js',
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: require.resolve('jquery'),
loader: 'expose-loader?jQuery!expose-loader?$'
}
],
},
plugins: [
// new CleanWebpackPlugin(['src/main/webapp/assets']),
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
}),
new UglifyJsPlugin({
test: /\.js$/,
sourceMap: process.env.NODE_ENV === "development"
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, './src/main/webapp/js')
}
};
When above code compiles , console throws this error
vendor.js:1 Uncaught ReferenceError: webpackJsonp is not defined
at vendor.js:1
And when i try to use this
externals: {
jquery: 'jQuery'
}
It throws
vendor.js:1 Uncaught ReferenceError: jQuery is not defined
at Object.231 (vendor.js:1)
at o (common.js:1)
at Object.228 (vendor.js:1)
at o (common.js:1)
at window.webpackJsonp (common.js:1)
at vendor.js:1
And i using jquery in my core js file import $ from 'jquery'.
What did i do wrong ? any help ? Thank you.
So there are few themes in your webpack.config.js, some of which conflict. Just going to list them so I can better understand what I think you are trying to achieve.
Theme 1
You have an entry called vendor that is clearly referencing a minified jQuery library you have presumably downloaded and placed in the directory specified.
Theme 2
You also have an expose-loader that is essential exposing the jquery library from its node_modules probably listed in the dependencies of your package.json.
This makes the jquery in the node_modules available as $ and jQuery in the global scope of the page where your bundle is included.
Theme 3
You also have included the ProvidePlugin with configuration for jQuery.
The ProvidePlugin is supposed to inject dependencies into the scope of your module code, meaning you do not need to have import $ from 'jquery' instead $ and jQuery will already be available in all of your modules.
Conclusion
From what I have gathered I think you're trying to bundle jQuery from the static file at ./src/main/webapp/js/vendor/jquery-3.3.1.min.js in a vendor bundle.
You are then trying to expose the libraries in the vendor bundle to the global scope (jQuery).
Then also have your application code able to import jQuery from what is made available by the vendor bundle in the global scope.
Answer
So if that is what you are doing you need to do the following things.
Firstly, check in your package.json files dependencies for jquery. If its there you want to remove it, there's no need for it if you're going to use your jquery-3.3.1.min.js file instead to provide jQuery to your application.
Secondly, change your test of the expose-loader to trigger when it sees your jquery-3.3.1.min.js file in your entries, not resolve it from the jquery dependency from your node_modules.
This regex pattern should do the trick.
{
test: /jquery.+\.js$/,
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
}
Thirdly, remove the ProvidePlugin if you're going to import the library explicitly with import $ from 'jquery' you do not need it.
Lastly, you need to tell webpack when it sees an import for jquery it can resolve this from window.jQuery in the global scope. You can do this with the externals configuration you already referenced.
externals: {
jquery: 'jQuery'
}
With all these changes you should end up with a webpack.config.js file that looks like this.
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
entry: {
vendor: [
'./src/main/webapp/js/vendor/jquery-3.3.1.min.js',
// './src/main/webapp/js/vendor/fs.js',
'./src/main/webapp/js/vendor/google-adsense.js',
'./src/main/webapp/js/vendor/jquery.menu-aim.min.js',
'./src/main/webapp/js/vendor/jquery.touchSwipe.min.js',
],
app: './src/main/assets/js/desktop/app.js',
mobile: './src/main/assets/js/mobile/app.js',
touch: './src/main/assets/js/touch/app.js',
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /jquery.+\.js$/,
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
}
],
},
plugins: [
// new CleanWebpackPlugin(['src/main/webapp/assets']),
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
}),
new UglifyJsPlugin({
test: /\.js$/,
sourceMap: process.env.NODE_ENV === "development"
})
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, './src/main/webapp/js')
},
externals: {
jquery: 'jQuery'
}
};
I hope that does not just give you the answer but enough explanation as to where you were going wrong.

Webpack 2: shimming like RequireJS for jQWidgets?

I’m migrating from a RequireJS project to Webpack.
The latter is new to me, I’m using this as a learning exercise.
In RequireJS I could register stuff like this:
shim: {
'jqxcore': {
exports: "$",
deps: ["jquery"]
},
'jqxtree': {
exports: "$",
deps: ["jquery", "jqxcore"]
},
'jqxbutton': {
exports: "$",
deps: ["jquery", "jqxcore"]
},
'jqxsplitter': {
exports: "$",
deps: ["jquery", "jqxcore"]
},
'jqxmenu': {
exports: "$",
deps: ["jquery", "jqxcore"]
}
}
and then just require “jqxsplitter” for example like so:
import "jqxsplitter"
and stuff would be correctly registered and loaded.
Now I was looking at a couple of guides/tutorials/takes I found on migrating from RequireJS to Webpack, such as this one and this one.
So following those insights I’m trying something like this in my webpack.config.js:
"use strict";
// Required to form a complete output path
const path = require("path");
// Plagin for cleaning up the output folder (bundle) before creating a new one
const CleanWebpackPlugin = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
// Path to the output folder
const bundleFolder = "./wwwroot/";
// Path to the app source code
const appFolder = "./app/";
module.exports = {
// Application entry point
entry: {
main: appFolder + "index.ts",
vendor: [
"knockout",
"jquery",
"jqxcore"
],
jqxsplitter: "jqxsplitter"
},
// Output file
output: {
filename: "[name].js",
chunkFilename: "[name].js",
path: path.resolve(bundleFolder)
},
module: {
rules: [{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/
}, {
test: /\.html?$/,
loader: "html-loader" //TODO: file-loader?
}],
loaders: [{
test: /jqxcore/,
loader: "imports?jquery!exports?$"
}, {
test: /jqxsplitter/,
loader: "imports?jquery,jqxcore!exports?$"
}]
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
alias: {
"jqxcore": "jqwidgets-framework/jqwidgets/jqxcore",
"jqxsplitter": "jqwidgets-framework/jqwidgets/jqxsplitter"
}
},
plugins: [
new CleanWebpackPlugin([bundleFolder]),
new HtmlWebpackPlugin({
filename: "index.html",
template: appFolder + "index.html",
chunks: ["main", "vendor"]
}),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
filename: "vendors.js",
minChunks: Infinity
})
],
devtool: "source-map"
};
the relevant part (I assume) being
module: {
loaders: [{
test: /jqxcore/,
loader: "imports?jquery!exports?$"
}, {
test: /jqxsplitter/,
loader: "imports?jquery,jqxcore!exports?$"
}]
},
It’s pretty clear how the syntax of “imports/exports” is supposed to be the equivalent of RequireJS’ “deps” and “exports”.
However when I do this in my index.ts file (app root):
import "jqwidgets-framework/jqwidgets/jqxsplitter";
I get the “jqxBaseFramework is undefined” error when running my app.
I’ve found references to this error on the forums of jQWidgets, but none of the answers seem to REALLY tackle the issue or include things like the AOT compilation, which doesn’t apply to my situation because I’m not using Angular.
I've posted this same question on the jQWidges forums, but so far no actual answer (going on two weeks now), only a single generic answer saying I should load jqxcore.js before jqxwhateverplugin.js.
Well yes, obviously, that's what I'm trying to accomplish using the shimming after all.
Any ideas?
Well I ended up deep diving and figuring it out for myself.
Here's the solution should anyone find themselves in the same or a similar boat.
If you beautify the jQWidgets script files jqxcore.js, you'll see it creates a what would normally be a global variable called "jqxBaseFramework", which will of course never be exposed globally, only within its own module. And there lies the problem.
The solution is to use this configuration:
module: {
rules: [{
test: /jqxcore/,
use: "exports-loader?jqxBaseFramework"
}, {
test: /jqxknockout/,
use: ["imports-loader?jqxBaseFramework=jqxcore,ko=knockout", "exports-loader?jqxBaseFramework"]
}, {
test: /jqxsplitter/,
use: "imports-loader?jqxBaseFramework=jqxknockout"
}]
},
resolve: {
...
alias: {
"knockout": "knockout/build/output/knockout-latest",
"jqxcore": "jqwidgets-framework/jqwidgets/jqxcore",
"jqxknockout": "jqwidgets-framework/jqwidgets/jqxknockout",
"jqxsplitter": "jqwidgets-framework/jqwidgets/jqxsplitter"
}
},
I guess once it clicks, this all makes sense.
The jqxcore module will now export its jqxBaseFramework variable with the same name.
I added in knockout support while at it.
jqxknockout expects two global variables to work normally: ko (knockout) and jqxBaseFramework.
So now we tell webpack that whenever jqxknockout is loaded, it should load the jqxcore module and assign its export to a module-local variable called "jqxBaseFramework" and load the knockout module and assign its export to a module-local variable called "ko".
This effectively equates to prepending the following code to the jqxknockout.js script:
var jqxBaseFramework = require("jqxcore");
var ko = require("knockout");
The script can now execute again because those two variables are found.
I added the export loader to export the same, but now processed/augmented jqxBaseFramework variable from jqxknockout.
jqxSplitter normally only needs jqxCore to work, but I want to use it with knockout, always. So instead of importing jqxBaseFramework from jqxCore for jqxSplitter, I'm getting it from jqxKnockout, so all the pieces are in place.
So now when I add this code to whatever file I'm in:
import "jqwidgets-framework/jqwidgets/jqxsplitter";
Webpack will require jqxknockout and its export for it, being jqxBaseFramework, which in turn will require jqxcore and knockout et voilà, the whole thing is wired up beautifully.
Hope this helps someone!

Use fullcalendar with webpack

I use npm, webpack and FullCalendar, but I get the following error in the browser console when using fullcalendar:
main.js:37556 Uncaught TypeError: (0 , _jquery2.default)(...).fullCalendar is not a function
How do I fix this?
I use FullCalendar 3.0.0-beta and jquery 3.1.0. My code is below.
index.js:
import $ from 'jquery'
import jQueryUI from 'jquery-ui'
import moment from 'moment'
import fullCalendar from 'fullcalendar'
$('#timetable').fullCalendar({
editable: true,
firstDay: 1,
droppable: true,
})
webpack.config.js:
var path = require("path")
var webpack = require("webpack")
var BundleTracker = require("webpack-bundle-tracker")
module.exports = {
context: __dirname,
entry: [
'fullcalendar',
'./static/index',
],
output: {
path: path.resolve('./static/bundles/'),
filename: "[name].js",
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.js'],
},
module: {
loaders:[
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015'] } }
]
}
}
I know I am somewhat late to the party here, but I thought I'd answer anyway in case somebody hits this up on Google.
Whenever I run into a jQuery Plugin with Webpack (which FullCalendar is), I need to make sure that jQuery itself is exposed to the global namespace before the plugin will work through require/import.
My webpack.config.js:
var webpack = require("webpack")
var path = require("path")
var ExtractTextPlugin = require("extract-text-webpack-plugin")
var HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
entry: {
app: "./index.js",
vendor: [
"jquery",
"moment",
"fullcalendar"
]
},
output: {
path: path.join(__dirname, '../../public'),
publicPath: '/',
filename: "scripts/app.[chunkhash].js"
},
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style", ["css"]) },
{ test: require.resolve('jquery'), loader: 'expose?$!expose?jQuery' },
{ test: require.resolve('moment'), loader: 'expose?moment' }
]
},
resolve: {
alias: {
jquery: path.resolve(path.join(__dirname, '../..', 'node_modules', 'jquery')),
fullcalendar: 'fullcalendar/dist/fullcalendar'
}
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.CommonsChunkPlugin({ names: ["vendor"], filename: "scripts/[name].[chunkhash].js" }),
new ExtractTextPlugin("styles/[name].[chunkhash].css"),
new HtmlWebpackPlugin({
template: "index.html.handlebars"
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
};
The relevant part is where jquery and moment are forced to be in the global namespace via the loader: 'expose?$!expose?jQuery' syntax.
Second, because fullcalendar is packaged in a way that the require can't automatically pick it up, I setup an alias so that I can have a clean package name. This is the alias: { fullcalendar: 'fullcalendar/dist/fullcalendar' } bit.
These two let me load fullcalendar via require/import and use it as I normally would.
The styles also need to be loaded. For this one I have not created aliases yet, so I just did a relative path to the css file:
#import "../../../node_modules/fullcalendar/dist/fullcalendar.css";
You can replace fullcalendar.js with fullcalendar.min.js to avoid recompressing, but for my use case because I was bundling all the vendor JS files together, I thought I would get better compression if I had more files concatenated. (Ditto for CSS fullcalendar.css with fullcalendar.min.css)
Disclaimer: I don't know if this is the "correct" way of doing this, but I know it took me a fair bit of trial and error with webpack to get jQuery plug ins like FullCalendar and Select2 to work, and this shell and method did make it easy.
For reference, links to the relevant files in a public repo where I use this pattern:
webpack.config.js: https://github.com/thegrandpoobah/mftk-back-office/blob/e531de0a94130d6e9634ba5ab547a3e4d41c5c5f/app/src/public/webpack.config.js
style scss: https://github.com/thegrandpoobah/mftk-back-office/blob/e531de0a94130d6e9634ba5ab547a3e4d41c5c5f/app/src/public/styles/main.scss
module where I use fullcalendar: https://github.com/thegrandpoobah/mftk-back-office/blob/e531de0a94130d6e9634ba5ab547a3e4d41c5c5f/app/src/public/students/index.js#L277
This is a step by step guide based on the data from above and other sources. First make sure you have moment.js installed:
npm install moment
Then make sure you have the fullcalendar version 3.10.2, which is the latest in version 3 which is optimized not bundling jQuery nor moment.js , and although it's not the latest version, it uses the old syntax, which won't break compatibility with legacy code:
npm install fullcalendar#3.10.2
Then install script-loader
npm install --save-dev script-loader
If you are using Laravel, then in resources/js/bootstrap.js add the following lines below bootstrap and jquery (note the use of script-lader!) :
window.moment = require('moment');
require('script-loader!fullcalendar/dist/fullcalendar');
require('script-loader!fullcalendar/dist/locale-all');
Then add the css style in resources/sass/app.scss:
#import '~fullcalendar/dist/fullcalendar.min.css';
Finally do:
npm run dev
Or, for production:
npm run prod
That's all
I think I found an even easier solution.
We're using fullcalendar and scheduler. We're converting from Rails sprockets to webpack. Adding fullcalendar to a lazyloaded chunk with webpack caused it to introduce two additional moments and jquerys (yep two) which, of course, didn't pick up our configuration changes as those where done on the original version in our chunked vendor file.
Ideally we just wanted fullcalendar included with no module processing (it does absolutely nothing and is totally unnecessary). Fortunately you can do this with webpack's script-loader.
require('script-loader!fullcalendar/dist/fullcalendar.js')
And you're done. Same with the scheduler. It loads it in isolation and unprocessed which is exactly what you want with a jquery plugin.
With webpack 5, below code solves the issue:
module: {
rules: [
{
test: require.resolve('jquery'),
loader: 'expose-loader',
options: {
exposes: ["$", "jQuery"]
}
},
{
test: require.resolve('moment'),
loader: 'expose-loader',
options: {
exposes: "moment"
}
},
{
test: require.resolve('fullcalendar'),
use: [
{
loader: 'script-loader',
options: 'fullcalendar/dist/fullcalendar.js'
}
]
},
{
test: require.resolve('fullcalendar-scheduler'),
use: [
{
loader: 'script-loader',
options: 'fullcalendar/dist/fullcalendar-scheduler.js'
}
]
},
]
},
I used fullCalendar for example:
$("#fullcalendar-activities").fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
events: events,
defaultView: 'month'
});

Make webpack's library output compatible with babel6

Babel's 6th version changes the functioning of export default and in particular its relation with commonjs require.
To summarise, while until babel5, require('module') where giving the default export of the module, it now always returns the module object containing all of the exports of the module.
If one only wants the default, he/she must use require('module').default.
As explained here, there is very good reasons behind this and the aim of this question is not to break or hack this behaviour.
However, if one is building a library, he/she usually does not want to distribute a module but the export value of his library (e.g. a function, whatever module system is used internally).
This is well dealt with by webpack and the output.library configuration when using commonjs or AMD. Because prior babel's versions allowed the default export to be required with commonjs, babel was also compatible with this mechanism. However it is not the case anymore: the library now always provides an es6 module object.
Here is an example.
src/main.js
export default "my lib content";
webpack.config.js
var path = require("path");
var webpack = require("webpack");
module.exports = {
entry: {
lib: [ path.resolve(__dirname, "src/main.js") ],
},
output: {
path: path.join(__dirname, "dist"),
filename: "mylib-build.js",
library: 'myLib'
},
module: {
loaders: [
{
test: /\.js$/,
loader: "babel",
include: path.join(__dirname, "src"),
query: { presets: ['es2015'] }
}
]
}
};
test.html
<html>
<head></head>
<body>
<script src="dist/mylib-build.js"></script>
<!-- `myLib` will be attached to `window` -->
<script>
console.log(JSON.stringify(myLib)); // { default: "my lib content" }
</script>
</body>
</html>
This is a very simple example but I obviously want the export of mylib to be the string "my lib content" instead of { default: "my lib content" }.
One solution could be to create an export source file in commonjs to perform the transformation:
module.exports = require('./main').default;
However I find this solution quite poor. One should be able to solve it at the compilation level, without changing the source code.
Any idea?
Was just going at this my self. Whether one like to call it a workaround or solution, there seem to be a Babel plugin that "solve it".
Using the plugin babel-plugin-add-module-exports as referenced in https://stackoverflow.com/a/34778391/1592572
Example config
var webpackOptions = {
entry: {
Lib1: './src/Lib1.js',
Lib2: './src/Lib2.js'
},
output: {
filename: "Master.[name].js",
library: ["Master","[name]"],
libraryTarget: "var"
},
module: {
loaders: [
{
loader: 'babel',
query: {
presets: ['es2015'],
plugins: ["add-module-exports"]
}
}
]
}
};
This yields Master.Lib1 to be lib1 instead of Master.Lib1.default.
Webpack 2 now supports es6 modules which partially solves this issue. Migrating from webpack 1 to webpack 2 is relatively painless. One just needs to remember to disable babel's es6 module to commonjs conversion to make this work:
.babelrc
{
"presets": [
["es2015", {"modules": false}]
]
}
However, unfortunately, it does not work properly with export default (but an issue is opened, hopefully a solution will be released eventually).
EDIT
Good news! Webpack 3 supports the output.libraryExport option that can be used to directly expose the default export:
var path = require("path");
var webpack = require("webpack");
module.exports = {
entry: {
lib: [ path.resolve(__dirname, "src/main.js") ],
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "mylib-build.js",
library: "myLib",
// Expose the default export.
libraryExport: "default"
},
module: {
loaders: [
{
test: /\.js$/,
loader: "babel",
include: path.resolve(__dirname, "src")
}
]
}
};
You can use this solution (this is more like workaround, but it allow you to keep your sources from change):
There is a loader called callback-loader. It allow you to change your sources in a build time by calling a callback and put a result instead of it. In other words you can turn all you require('module') into a require('module').default automatically in a build time.
Here is your config for it:
var webpackConfig = {
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'callback' },
...
]
},
...
callbackLoader: {
require: function() {
return 'require("' + Array.prototype.join.call(arguments, ',') + '").default';
}
}
};

How to require 'ace-builds/ace' with Webpack and noParse option

I'm currently trying to require ace-builds (installed from bower) with webpack. Since it's a huge lib, I'm adding the whole folder to noParse option. I'm running webpack with -d option on terminal.
The problem is: when my code tries to require it, it is an empty object. Also, it's not loaded by the browser. Here are some information of what I'm doing:
My file:
// custom_editor.js
// ace-builds are aliased by ace keyword
var Ace = require('ace/ace'); // This is an empty Object when I'm debugging with breakpoints
Config file:
// webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
form: path.join(__dirname, 'static/main_files/form.js'),
vendor: [
'jquery',
'react',
'underscore',
'query-string',
'react-dnd',
'react-select-box'
]
},
output: {
path: path.join(__dirname, 'static/bundle'),
filename: '[name].bundle.js'
},
module: {
loaders: [{
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM'
}],
noParse: [
/ace-builds.*/
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
root: [
__dirname,
path.join(__dirname, 'static'),
path.join(__dirname, 'node_modules')
],
alias: {
jQueryMask: 'node_modules/jquery-mask-plugin/dist/jquery.mask',
twbsDropdown: 'node_modules/bootstrap-sass/assets/javascripts/bootstrap/dropdown',
'twbs-datetimepicker': 'node_modules/eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker',
ace: 'bower_components/ace-builds/src',
'select-box': 'node_modules/react-select-box/lib/select-box',
queryString: 'node_modules/query-string/query-string',
moment: 'node_modules/moment/moment'
}
},
plugins: [
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
};
It was not loaded on Chrome's Network panel
It is showing on Chrome's Sources panel (Don't know why because no ace.map file were loaded either)
Really running out of ideas of what I'm doing wrong here. Is there any good example that I can clone and test? (It can be another lib as well).
Use brace. It's a browserify compatible version of the ace editor which also works with webpack. Version 0.5.1 is using ace 1.1.9.
https://github.com/thlorenz/brace

Categories

Resources