webpack-contrib / imports-loader Goto Github PK
View Code? Open in Web Editor NEWImports Loader
License: MIT License
Imports Loader
License: MIT License
The example configuration file for using the imports loader is wrong:
// ./webpack.config.js
module.exports = {
...
module: {
loaders: [
{
test: require.resolve("some-module")
loader: "imports?this=>window"
}
]
};
The test property is according to the webpack documentation a condition that "may be a RegExp, a string containing the absolute path, a function(absPath): bool, or an array of one of these combined with 'and'.". require.resolve
, on the other hand, returns a module id that is either a number or a string, depending on the environment.
Recently, I study webpack via https://webpack.js.org/guides/shimming/#granular-shimming.
Below code is my part of webPack config:
{
test: require.resolve('./src/index.js'),
use: 'imports-loader?this=>window',
},
when run webpack cmd,there will log exception :
ERROR in ./src/index.js
Module build failed (from ./node_modules/imports-loader/dist/cjs.js):
ValidationError: Invalid options object. Imports Loader has been initialized using an options object that does not match the API schema.
- options should be one of these:
object { imports, … } | object { wrapper, … } | object { additionalCode, … }
Details:
* options has an unknown property 'this'. These properties are valid:
object { imports, … } | object { wrapper, … } | object { additionalCode, … }
* options misses the property 'imports' | should be any non-object.
* options misses the property 'wrapper' | should be any non-object.
* options misses the property 'additionalCode' | should be any non-object.
thx!
Like the title says if I use the imports-loader like this:
require("imports-loader?jQuery=jquery!bootstrap-sass");
And I have an "externals" configuration provided in my webpack configuration:
{
...
externals: {
"bootstrap-sass": "jQuery"
}
...
}
The externals configuration is ignored.
Workaround:
When configuring the "imports-loader" via webpack configuration:
{
...
module: {
rules: [
{
test: require.resolve("bootstrap-sass"),
use: "imports-loader?jQuery=jquery",
}
]
}
}
everything works as expected.
Any chance this is getting fixed so in both cases the "externals" configuration is taken into account?
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
In my project, I use import
rather than require
- this means that using imports-loader
makes me end up with files that have both import
and require
.
Normally, this wouldn't be an issue, however, it seems Webpack handles these two slightly differently - namely, import
seems to take precedence over require
- and there are modules like babel-polyfill which are designed to be the first thing imported, which is causing me trouble (I'm aware this is not the best example, as babel-polyfill can be imported as an entry, but didn't want to digress too much).
Perhaps more importantly, import
tends to be more versatile, allowing things like importing a single export.
Any objections to adding an extra syntax (e.g. "=+", with "something=+module" resulting in import something from "module"
and "{e}=+module" resulting in import {e} from "module"
) that would cause imports-loader
to produce import
syntax rather than require? Happy to do a PR for that.
Hi , i'm trying to use this loader in my vue project but it's not work. I wanna introduce wow.js
plugin that does not depend on jQuery .
am i miss something ?
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
},
{
test: require.resolve("../static/wow.min.js"),
loader: "imports-loader"
}
]
}
in components.vue
require('imports-loader?../../static/js/wow.min.js');
Does this loader support Webpack 2? If so, how would you specify the options with the new rules
API?
For example. I have this:
{
test: /globalize/,
loader: 'imports?define=>false',
},
I was thinking:
{
test: /globalize/,
use: [{ loader: 'imports-loader', options: { 'define=>false': '' } }],
}
But I'm unsure, and it seems odd...
Documentation Is:
I did some experimenting and it looks like you can specify additionalCode
inline. Currently the examples are only of type=
and imports=
.
Add an example like:
import myLib from 'imports-loader?additionalCode=var%20require%20=%20false;!./example.js';
// Adds the following code to the beginning of example.js:
// var require = false;
Unfortunately, I don't have time to repro this issue but I'm very sure ( and have just confirmed) when imports-loader and expose-loader are both applied on the same file, doing imports loader this=>window will not work since the imports-loader will try to 'call' the additionally wrapped function generated by expose-loader instead of the actual module function.
Solution
Remove expose-loader on the file and imports-loader will start to work
Hi,
I was trying to accomplish something amazing with this library, but I found out that I got blocked by one simple task that could enhance a lot this library.
What I need basically is a way to expand the IIFE with custom arguments, see
https://github.com/webpack-contrib/imports-loader/blob/master/index.js#L26
These two blocks would be really awesome if there could be a way to configure which argument will take in and which one could be passed in the .call
.
Can you please think about a way? I will see if I will be able to do a PR maybe tomorrow.
Thank you and best regards,
Julian
In Imports-Loader 0.8.0, you could use define=>false
to short circuit AMD modules in older style jQuery plugins (see https://stackoverflow.com/questions/35531126/how-to-use-scrollmagic-with-gsap-and-webpack). However this functionality seems to have changed in 1.1.0 and I'm not exactly sure what the new style should be. I've tried additionalCode: 'var define = false'
and various imports, but no luck. With additionalCode
specifically I get a TypeError: false is not a function
in the browser's debugger. Any thoughts on how this can be alleviated?
Also, define=>false
used to be specifically documented, but the equivalent isn't in 1.1.0 (at least as far as I can tell), would be nice if the analogue would be written down now.
When doing something like this
require('imports?this=>global!bootstrap');
Where bootstrap is defined as an alias
resolve: {
alias: {
// Bootstrap
'bootstrap' : path.join(PATH_JS_VENDOR, 'bootstrap/bootstrap'),
}
},
doesn't seem to work
Nice work with imports-loader!
I'm seeing errors of the following form, which are being thrown for many libraries (not specifically jQuery) while importing (see attached):
My webpack.config.js is using webpack 2 and is patterned as:
const config = {
entry: ...,
...,
resolve: {
modules: ['.', 'node_modules'],
alias: {
...,
'jQuery': path.resolve('node_modules/jquery/dist/jquery.min'),
'$': path.resolve('node_modules/jquery/dist/jquery.min'),
'jquery': path.resolve('node_modules/jquery/dist/jquery.min'),
...
},
module: {
loaders: [
{test: /\(js|jsx)$/, use: 'babel-loader'}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({minimize: true}),
new webpack.ProvidePlugin({
'$': 'jQuery',
'jQuery': 'jquery',
...
}),
...
]
}
}
Any help would be greatly appreciated!
I think this might be Babel's issue but I'm posting here because others are likely to encounter it and it might be worth considering on this end.
Three.js provides some classes that aren't available by default but can be treated as mixins by requiring them. Unfortunately, they all expect a global THREE
so I've been working around it with this loader. My process has been:
require('imports-loader?THREE=three!/three/examples/js/loaders/FBXLoader.js');
import { FBXLoader } from 'three'
After that, I'm able to call upon FBXLoader
without any trouble.
Since upgrading to Babel 7, I get this warning:
"export 'FBXLoader' was not found in 'three'
That happens as a result of the import
call, not the require. There's an issue over at Babel that almost describes my problem except I'm not using Babel's TypeScript integration, which leads me to wonder if this isn't due to TypeScript and is instead something that can be addressed here. I unfortunately don't know enough about the import/export process to really troubleshoot on my own.
As it stands, this is being reported as a warning, not an error, so my webpack builds succeed, but it's awfully annoying and hides build output information that I'd like to see. I'm happy to take this elsewhere if you determine this is truly babel's problem. I appreciate your help on this.
webpack.config.js
{ test: /\.js$/, loader: 'envify!babel'}
this is wrong
!function (a, b) {
"function" == typeof define && (define.amd || define.cmd) ? define(function () {
return b(a);
}) : b(a, !0);
}(undefined, function (a, b) {}.call(window));
this is correct
!function (a, b) {
"function" == typeof define && (define.amd || define.cmd) ? define(function () {
return b(a);
}) : b(a, !0);
}(this, function (a, b) {}.call(window));
// webpack v4.x code
module: {
rules: [
{
test: require.resolve('./src/index.js'),
use: 'imports-loader?this=>window',
}
]
}
// use chainWebpack not working
chainWebpack: config => {
config.module
.rule('.js')
.test(require.resolve('./src/libs/test.js'))
.use('imports-loader')
.loader('imports-loader?this=>window')
}
The expression imports?window.jQuery=jquery!angular
generates the following
/*** IMPORTS FROM imports-loader ***/
var window = (window || {});
window.jQuery = require("jquery");
require('./angular');
When webpack wraps this in a function expression, the window
referenced in the initialization of the localwindow
is the local window
rather than the global window
. This is fine for contained modules, but in this case the module is just a stub that loads another module where the private window
isn't visible.
I want to set window.jQuery
. According to docs I have to do this:
},{
test: require.resolve("jquery"),
loader: "imports?$=jquery,jQuery=jquery,jQuery=>window"
}],
But it doesn't work, here is console output:
console.log('[$] :', $);
console.log('[jQuery] :', jQuery);
console.log('[window.jQuery]', window.jQuery);
[$] : function ( selector, context ) { ... }
[jQuery] : function ( selector, context ) { ... }
[window.jQuery] undefined
// It works only after explicit assignment:
window.jQuery = $;
console.log('[window.jQuery]', window.jQuery);
[window.jQuery] : function ( selector, context ) { ... }
Question. What;'s wrong with config? Why the following line doesn't sets window.jQuery
:
loader: "imports?$=jquery,jQuery=jquery,jQuery=>window"
What is the right approach to set window.jQuery
with imports-loader
?
In an original way, I reference the JS library globally by using the <script> tag. But it's not the way in webpack.
So I found 'imports-loader'. The problem is my JS library is not install by npm (like the jQuery or angular), it's in my src/assets/ folder.
How can I add my JS library to window object?
What I'm trying to do with a custom loader, is stop the chain in pitch phase, because I take another source file, but the rest of the chain (remainingRequest) should be added as an import/require, so I would use this imports-loader inline, but the name will have inline loaders too. Is there a way to escape the !
or to use this with inline loaders?
There are modules which I want to import only for the side effects they provide - in this case I only really need require("module");
and not var module = require("module");
- would this make sense to add?
I was thinking of something like void=module
resulting in dropping the var
, but then it occurred this would mean only one of these would be possible (since we can't have duplicate keys). Perhaps something like ~module
would work? Happy to do a PR, if there are no objections.
A lot of plugins for jquery etc. want to find jQuery on the window.
Suggestion: if the key contains a period, don't use var, just assign.
I try to import jquery.ui.position for a another file like so:
module: {
loaders: [
{
test: /index\.js$/,
loader: 'imports?jquery.ui.position' // This line throws an error
}
]
},
which gets an error much like the following.
ERROR in ./index.js
Module parse failed: S:\Github\webpack_import_loader_bug\node_modules\imports-loader\index.js?jquery.ui.position!S:\Github\webpack_import_loader_bug\index.js Unexpected token (2:10)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:10)
at Parser.pp$4.raise (S:\Github\webpack_import_loader_bug\node_modules\acorn\dist\acorn.js:2221:15)
at Parser.pp.unexpected (S:\Github\webpack_import_loader_bug\node_modules\acorn\dist\acorn.js:603:10)
at Parser.pp.semicolon (S:\Github\webpack_import_loader_bug\node_modules\acorn\dist\acorn.js:581:61)
at Parser.pp$1.parseVarStatement (S:\Github\webpack_import_loader_bug\node_modules\acorn\dist\acorn.js:918:10)
at Parser.pp$1.parseStatement (S:\Github\webpack_import_loader_bug\node_modules\acorn\dist\acorn.js:706:19)
at Parser.pp$1.parseTopLevel (S:\Github\webpack_import_loader_bug\node_modules\acorn\dist\acorn.js:638:25)
at Parser.parse (S:\Github\webpack_import_loader_bug\node_modules\acorn\dist\acorn.js:516:17)
at Object.parse (S:\Github\webpack_import_loader_bug\node_modules\acorn\dist\acorn.js:3098:39)
at Parser.parse (S:\Github\webpack_import_loader_bug\node_modules\webpack\lib\Parser.js:902:15)
at DependenciesBlock. (S:\Github\webpack_import_loader_bug\node_modules\webpack\lib\NormalModule.js:104:16)
at DependenciesBlock.onModuleBuild (S:\Github\webpack_import_loader_bug\node_modules\webpack-core\lib\NormalModuleMixin.js:310:10)
at nextLoader (S:\Github\webpack_import_loader_bug\node_modules\webpack-core\lib\NormalModuleMixin.js:275:25)
at S:\Github\webpack_import_loader_bug\node_modules\webpack-core\lib\NormalModuleMixin.js:292:15
at runSyncOrAsync (S:\Github\webpack_import_loader_bug\node_modules\webpack-core\lib\NormalModuleMixin.js:160:12)
at nextLoader (S:\Github\webpack_import_loader_bug\node_modules\webpack-core\lib\NormalModuleMixin.js:290:3)
at S:\Github\webpack_import_loader_bug\node_modules\webpack-core\lib\NormalModuleMixin.js:259:5
at Storage.finished (S:\Github\webpack_import_loader_bug\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:38:16)
at S:\Github\webpack_import_loader_bug\node_modules\graceful-fs\graceful-fs.js:78:16
at FSReqWrap.readFileAfterClose as oncomplete
After much hair-pulling and gnashing of teeth I try to alias jquery.ui.position as jquery_ui_position, which works as expected. Apparently the dots within the module name throw the import loader off.
Am I supposed to escape the dots in some fashion? The documentation doesn't say.
I have set up a tiny example project which demonstrates the issue at https://github.com/sgarcialaguna/import-loader-bug
Hey 😄
I'm trying to achieve the following :
const { JSDOM } = require('jsdom');
const XMLSerializer = require('xmlserializer');
const dom = new JSDOM().window;
global.window = {};
global.document = dom.document;
global.Document = dom.Document;
global.Node = dom.Node;
global.DOMParser = dom.DOMParser;
global.XMLSerializer = XMLSerializer;
global.navigator = {
userAgent: ''
};
(this seems rough, but it's working, like this)
I'm trying to achieve this through webpack and imports loader. (the goal is to completely shim OpenLayers for use in Node.js)
I came up with the following
use: 'imports-loader?window.proj4=proj4,navigator=>{userAgent: ""},document={},XMLSerializer=xmlserializer'
But I'm struggling with the "dom" part.
Can I require a local file for complex shimming like this ?
Is that required anyway ? Is there a way to accomplish what I want without ? (I mean, the
new
invocation part)
Hi,
I've been stuck over the last few days on injecting jsrsasign into oauth-ng.
Latest test is
require('jsrsasign');
require('imports?KJUR=jsrsasign,KEYUTIL=jsrsasign!oauth-ng');
that gives me the following result at the beginning of oauth-ng in the bundle
var KJUR = __webpack_require__(462);
var KEYUTIL = __webpack_require__(462);
But what I actually would like to have is something equivalent to
var KJUR = __webpack_require__(462).KJUR;
var KEYUTIL = __webpack_require__(462).KEYUTIL;
Is there anyway to do that? (jsrsasign defines mutiples modules using the exports syntax, and those are the modules I want to inject, not the "container")
Thank you for your help, pulling my haire on this one
Hi, I am trying to use imports-loader
along with this library (only available from NuGet) :
https://www.nuget.org/packages/Microsoft.AspNet.SignalR.JS/2.2.0
This library is dependent on jQuery.
I have failed to make my import work :
var jQuery = require('jquery')
var signalR = require('imports?jQuery=jquery!../js/jquery.signalR-2.2.0.js')
and I don't know why :(
I've looked in the signalR library and sometimes $ is used, sometimes jQuery is used or window.$ or window.jQuery
How can I make this import work correctly?
Thanks!
Try importing jquery-migrate into a legacy jquery plugin, and you will get a compile error:
/node_modules/imports-loader/index.js?jQuery=jquery,this=>window,"jquery-igrate"!...node_modules/vh.jquery.ba-bbq/jquery.ba-bbq.js Unexpected token (4:4) You may need an appropriate loader to handle this file type. | var jQuery = require("jquery"); | (function() { | var "jquery-migrate" = require("\"jquery-migrate\""); | | /*!
My workaround is to create an alias but it would be nice if the import loader replaced invalid variable name characters with underscores or something.
You need to install that missing module called "imports-loader"
It seems that NPM is not a very good package manager. Install new modules via yarn:
To install Yarn ... go to https://yarnpkg.com
Then
$ sudo yarn add missing-module-name --dev/-D
See more details from
Migrating from npm to Yarn
https://yarnpkg.com/lang/en/docs/migrating-from-npm/
npm install --save-dev [package] yarn add [package] [--dev/-D]
I have several webpack.config.js in spread in different level of directories.
In a child webpack I do use: 'imports-loader?this=>window'
, and it looks for parent directory's node_modules
.
For other loaders I use form of require.resolve("style-loader")
to use the current directory's node_modules library.
Can I use form of require.resolve('imports-loader')
for use: 'imports-loader?this=>window'
?
Hello I'm trying to use this loader in my webpack.config.json
but just in the entry file
angular.module('clipApp', [])
.controller('AppCtrl', function () {
console.log('yeah!!!');
});
I'm getting an error
Uncaught TypeError: angular.module is not a function
am I missing something?
{
entry: path.resolve(PATHS.app, 'app'),
resolve: {
extensions: ['', '.js']
},
output: {
path: PATHS.build,
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.js$/,
loaders: ['imports-loader?angular'],
},
{
test: /\.html$/,
loader: 'ng-cache?prefix=[dir]',
include: path.resolve(PATHS.app, 'modules')
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=images/[name].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
],
include: PATHS.assets
}
]
},
plugins: [
new HtmlwebpackPlugin({
title: 'PNUD Admin',
template: 'templates/index.tpl'
})
]
}
This throws an error:
}, {
test: require.resolve("jquery"),
loader: ["imports?$=jquery,jQuery=jquery"]
}],
This error:
$ webpack --config webpack.development.config.js -cd --progress --watch
20% 1/6 build modulesc:\Users\user\app\node_modules\webpack-core\lib\LoadersList.js:58
if(element.loader) return element.loader.split("!");
^
TypeError: element.loader.split is not a function
at getLoadersFromObject (c:\Users\user\app\node_modules\webpack-core\lib\LoadersList.js:58:43)
at LoadersList.<anonymous> (c:\Users\user\app\node_modules\webpack-core\lib\LoadersList.js:78:12)
at Array.map (native)
at LoadersList.match (c:\Users\user\app\node_modules\webpack-core\lib\LoadersList.js:70:19)
at c:\Users\user\app\node_modules\webpack\lib\NormalModuleFactory.js:111:68
at c:\Users\user\app\node_modules\async\lib\async.js:726:13
at c:\Users\user\app\node_modules\async\lib\async.js:52:16
at done (c:\Users\user\app\node_modules\async\lib\async.js:246:17)
at c:\Users\user\app\node_modules\async\lib\async.js:44:16
at c:\Users\user\app\node_modules\async\lib\async.js:723:17
at c:\Users\user\app\node_modules\async\lib\async.js:167:37
at c:\Users\user\app\node_modules\enhanced-resolve\lib\UnsafeCachePlugin.js:29:4
at onResolved (c:\Users\user\app\node_modules\enhanced-resolve\lib\Resolver.js:39:10)
at innerCallback (c:\Users\user\app\node_modules\enhanced-resolve\lib\Resolver.js:89:22)
at loggingCallbackWrapper (c:\Users\user\app\node_modules\enhanced-resolve\lib\createInnerCallback.js:21:19)
at c:\Users\user\app\node_modules\tapable\lib\Tapable.js:134:6
at c:\Users\user\app\node_modules\enhanced-resolve\lib\ModulesInDirectoriesPlugin.js:55:11
at c:\Users\user\app\node_modules\enhanced-resolve\lib\Resolver.js:191:15
at c:\Users\user\app\node_modules\enhanced-resolve\lib\ModulesInDirectoriesPlugin.js:46:14
at loggingCallbackWrapper (c:\Users\user\app\node_modules\enhanced-resolve\lib\createInnerCallback.js:21:19)
at c:\Users\user\app\node_modules\tapable\lib\Tapable.js:134:6
at c:\Users\user\app\node_modules\enhanced-resolve\lib\Resolver.js:123:21
at c:\Users\user\app\node_modules\enhanced-resolve\lib\Resolver.js:191:15
at applyPluginsParallelBailResult.createInnerCallback.log (c:\Users\user\app\node_modules\enhanced-resolve\lib\Resol
s:104:30)
at loggingCallbackWrapper (c:\Users\user\app\node_modules\enhanced-resolve\lib\createInnerCallback.js:21:19)
at c:\Users\user\app\node_modules\tapable\lib\Tapable.js:134:6
at Tapable.<anonymous> (c:\Users\user\app\node_modules\enhanced-resolve\lib\DirectoryDescriptionFilePlugin.js:68:32)
at loggingCallbackWrapper (c:\Users\user\app\node_modules\enhanced-resolve\lib\createInnerCallback.js:21:19)
at c:\Users\user\app\node_modules\enhanced-resolve\lib\Resolver.js:123:21
at c:\Users\user\app\node_modules\enhanced-resolve\lib\Resolver.js:191:15
for example:
/* foo.js */
module.exports = 1;
/* bar.js */
module.exports = foo + 1;
/* baz.js */
console.log(bar);
i tried:
require('imports?bar=imports?foo!bar!baz'); // webpack error: can't resolve module 'bar'
// or
require('imports?foo,bar!baz'); // runtime error: 'foo' is not defined in bar.js
but neither worked.
do i use the wrong syntax or nested import is not supported? (if the latter, maybe i should use loader config or ProvidePlugin.)
I'm trying to use the imports loader in order to shim a module, but since it is pre-compiled I have it excluded with a noParse:
regexp. This means that the require(...)
calls injected by the imports loader don't work.
Any chance I could get this to work?
According to #39, imports-loader
should work with ES6 modules.
I see the same issue as described in #39:
[...]
ERROR in ./src/foobar.js 4:0
Module parse failed: 'import' and 'export' may only appear at the top level (4:0)
File was processed with these loaders:
* ./node_modules/imports-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
|
| (function() {
> export let bla = {
| doSomething: function() {
| console.log("this is " + this);
@ ./src/index.js 1:0-31 3:0-15
webpack 5.1.2 compiled with 1 error in 156 ms
Please see the demonstration repo at https://github.com/chkpnt/imports-loader-issue.
Just execute npm run-script dev
in the demonstration repo.
The documentation for imports-loader has a case for injecting a variable with a JS Object literal as follows:
import?config=>{size:50}
This works great, but once you try to add another property to this JS object in (what I considered to be) the obvious way:
import?config=>{size:50,color:2}
The imports-loader (indirectly via loaders-util) tokenizes on the comma and starts doing.. weird things (hard to describe, but it basically treats the {size:50
as a variable injection, and the color:2}
as a require injection.
The solution is easy enough once you understand what is going on (or read through the source code), just replace the comma with the URI encoded version %2C
. But you actually have to do this manually and can't depend on the encodeURIComponent
function (something to do with require context
? Not sure).
I'm guessing that this may throw a curve ball for people (like it did for me!) so it might be worthwhile to beef up the documentation to clarify this.
I'm still a bit new to webpack and all its modules and plug-ins, so I may be doing something wrong, so please do bear with me :)
{
entry : ["index.js", __dirname+"libs/jquery.js"]
}
Is there a benefit to use this plugin rather than packaging jqury
directly into index.js
?
If we can use imports?config=>{foo:true}
, using imports?config=>{foo:true,bar:false}
should also work. The inner comma is interpreted as a different value for the imports-loader and the result is invalid and unexpected JS code:
var config = {foo:true;
var bar:false}
Any workaround for this?
#{ test: require.resolve("./src/plugins/froala_editor.min"), loader: "imports?$=jQuery" } var``$=require("jquery");$('#edit').editable()
webpack chrome console error : Uncaught TypeError: $(...).editable is not a function!
why ?
somewhere in my dependency graph, I have a file with a format like this:
if (typeof define === 'function') {
// do some AMD stuff with `define`
} else {
var foo = require('etc etc etc');
}
If webpack parses this without imports-loader?define=>false
, then it tries to resolve a bunch of AMD modules that I don't have, since I am using npm
and commonjs. So I have this in my config file:
module: {
loaders: [
// try to totally disable AMD shit since we're just commonjs here
// this gets "universal" modules to skip trying to use AMD, since we
// don't have any of the dependecies set up in that case.
// @see https://github.com/webpack/imports-loader#disable-amd
{
test: /./,
loader: 'imports-loader?define=>false',
},
// ... more loaders
]
}
However, I see that imports-loader is inserting variables before any "use strict";
directives in my modules or my dependencies:
is there a better way to disable AMD in webpack? Is there a way to move "use strict"; above the imports-injected variables?
No errors
Invalid regular expression: invalid group specifier name
webpack.config.js
https://gist.github.com/killmenot/ca5f2efd020e7c5870fc671910e520b0
// app.js
import 'imports-loader?this=>window|jquery.appear'
import 'imports-loader?window.jQuery=jquery|jquery-countto'
Open in Safari (Chrome works OK)
I've installed version 3.3.1 of Bootstrap and version 1.11.1 of jQuery. In my entrypoint js file, I have:
require('imports?jQuery=jquery!bootstrap')
After building my javascript file without errors and running it in a browser I get a Uncaught ReferenceError: jQuery is not defined
error located in the Bootstrap code.
I see an inserted jQuery definition once in https://github.com/twbs/bootstrap/blob/master/dist/js/npm.js but not in any of the modules this module imports. The imported modules are what expect jQuery to have a definition.
Is there a way to import a variable into all modules under a certain point in the dependency tree (e.g., into Bootstrap and all of the modules it depends on) but not define it globally or at least not globally to non-Bootstrap modules?
I'm trying to setup Jest tests configuration for my project. I use imports-loader to load some old jQuery libs
import 'imports-loader!jquery-mousewheel'
When running tests with jest I get following error:
Cannot find module 'imports-loader!jquery-mousewheel' from 'SomeModule.js'
As a workaround, I mock all imports-loader in Jest config
"moduleNameMapper": {
"imports-loader?.*": "<rootDir>/internals/mocks/importsLoader.js"
},
// importsLoader.js
module.exports = 'IMPORTS_LOADER_MOCK';
How to configure it to actually import correct module?
I wanna do a simple thing - generate dynamic config depending on environment. So I do something like:
webpack.babel.js
import config from './config';
use: `imports-loader?APP_CONFIG=>(${JSON.stringify(config)})`
but get this error:
| /*** IMPORTS FROM imports-loader ***/
> var APP_CONFIG = ({"country":"UK";
| var "env":"development" = require("\"env\":\"development\"");
| var "src":" = ("src":" || {});
Maybe related to #33
/* foobar.js */
// ES6 export
const foobar = {
foo: 'bar'
}
export default foobar;
// is equivalent to
module.exports = {
default: foobar
}
/* foobar-log.js */
console.log(foobar);
So if I import foobar-log.js
with imports-loader
import 'imports?foobar=./foobar!./foobar-log'
It gives object with default. It seems there're no way toget just { foo: bar }
.
The GSAP library that I am loading requires access to the document object. I have research many solutions, but none have worked. How do I expose the document object to that plugin (or to all plugins)?
This page for instance: http://webpack.github.io/docs/shimming-modules.html
explains three potential solutions. For me, each one yields a different error message.
If I write import
{TimelineMax} from 'imports?this=>window!gsap';
I get the error
Cannot find module 'imports?this=>window!gsap'
The problem is not unique to GSAP; it happens with every library. Imports loader is not recognized by webpack. Even though it is in package.json, has been installed, and other loaders work fine.
"imports-loader": "0.6.5",
Any help appreciated.
37: var postfix = "\n" + postfixes.join("\n");
because if source contain sourcemap comment at the end without new line after, all build is failed with "unexpected end" error
Hi.,
I am trying to access window object inside main.js file by injecting it from index.js via imports-loader syntax and webpack-ing it.
ERROR in ./~/imports-loader?global=window!./main.js
Module not found: Error: Cannot resolve module 'window' in C:\Users\user\Desktop\webpack-dummy
@ ./~/imports-loader?global=window!./main.js 2:13-30
C:\Users\user\Desktop\webpack-dummy\dist\bundle.js:55
var global = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"window\""); e.code = 'M
ODULE_NOT_FOUND'; throw e; }())); ^
Error: Cannot find module "window"
C:\Users\user\Desktop\webpack-dummy\dist\bundle.js:62
}.call(window));
^
ReferenceError: window is not defined
C:\Users\user\Desktop\webpack-dummy\dist\bundle.js:55
var global = window;
^
ReferenceError: window is not defined
index.js
Tried this : require('imports?global=window!./main.js');
Tried this: require('imports?this=>window!./main.js');
Tried this : require('imports?global=>window!./main.js');
main.js
module.exports = ((function () {
window.myName = "Clark Kent";
console.log(window.myName);
return {};
})());
webpack.config.js
module.exports = {
entry: "./index.js",
output: {
path: 'dist',
filename: "bundle.js"
},
resolve: {
extensions: ['', '.js']
},
target: "web"
};
Module parse failed: /path/to/project/node_modules/imports-loader/index.js?this=>window!/path/to/project/src/entry.js 'import' and 'export' may only appear at the top level (4:0)
You may need an appropriate loader to handle this file type.
| (function() {
|
| import './NameSpace';
| import './Polyfill';
rules: [
{
test: regx,
use: [
{
loader: "imports-loader?this=>window",
},
],
},
],
But import 'imports-loader?this=>window./NameSpace';
this works fine.
Since webpack is capable of both, they default to AMD in this case, which can be a problem if the implementation is quirky.
First, thanks for providing this loader. I've seen plug and chug usages in a few StackOverflow posts that have helped me troubleshoot an issue.
What does it mean if "the implementation is quirky"? I started moving a project that uses <script> tags in html to using webpack. I had a few issues trying to use the popular Datatables library. There are a number of copy and paste solutions offered on the Datatables forums and stackoverflow that make use of imports-loader. I'd like to understand why issues pop such as: this/window/$ is undefined.
The "Shimming Modules" link in the readme points to a dead page.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.