Git Product home page Git Product logo

script-loader's Introduction

npm node deps chat

! NO LONGER MAINTAINED !

This module is deprecated and will no longer be maintained.

It has a known issue of generating non-deterministic hashes (see #49, #56, #60). Do not use it.

In most cases, you can replace the functionality by using raw-loader instead:

- import('script-loader!someScript.js')
+ import('raw-loader!someScript.js').then(rawModule => eval.call(null, rawModule.default))

If you need some transformations to be applied to the script you want to load, you may need to find or write yourself a separate loader for that. Some documentation that might be helpful:


Script Loader

Install

npm install --save-dev script-loader

Usage

Executes JS script once in global context.

⚠️ Doesn't work in NodeJS

Config (recommended)

import './script.exec.js';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.exec\.js$/,
        use: [ 'script-loader' ]
      }
    ]
  }
}

Inline

import 'script-loader!./script.js';

Options

Name Type Default Description
sourceMap {Boolean} false Enable/Disable Sourcemaps
useStrict {Boolean} true Enable/Disable useStrict

sourceMap

Type: Boolean Default: false

To include source maps set the sourceMap option.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.script\.js$/,
        use: [
          {
            loader: 'script-loader',
            options: {
              sourceMap: true,
            },
          },
        ]
      }
    ]
  }
}

useStrict

Type: Boolean Default: true

To disable use strict set the useStrict option to false.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.script\.js$/,
        use: [
          {
            loader: 'script-loader',
            options: {
              useStrict: false,
            },
          },
        ]
      }
    ]
  }
}

Maintainers


Juho Vepsäläinen

Joshua Wiens

Kees Kluskens

Sean Larkin

script-loader's People

Contributors

aymasse avatar dependabot[bot] avatar emememw avatar jakub-g avatar joshwiens avatar kevinzwhuang avatar lwr avatar michael-ciniawsky avatar munter avatar nornagon avatar shama avatar sokra avatar timpur avatar wuxiandiejia 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  avatar  avatar  avatar  avatar

script-loader's Issues

[Karma] Bundled file works in browser but can't be loaded in Karma

Hey guys,
my problem occurs in AngularJS 1.3 app. I have one JS file bundled with script-loader. Everything works great in the browser - app works the same as before. However I have a problem with loading this file into Karma config. I've reduced my config files so now it looks like this:

module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            'app/app.bundle.js'
        ],
        // the rest goes beneath but is not relevant to this issue
    });
};

Like I said there is no problem in the app but Karma throws an error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module edenred due to: Error: [$injector:modulerr] Failed to instantiate module expenseClaim due to: Error: [$injector:unpr] Unknown provider: USER_TYPE

So simply it has a problem with some dependencies - USER_TYPE is a constant in my app.
That the line it breaks - note that it doesn't on STATES_EXPENSE_PROFILES or $stateProvider.
.config(function ($stateProvider, STATES_EXPENSE_PROFILES, USER_TYPE) {

I'm using [email protected], [email protected].

I'd appreciate any clues,
best, G.

Order of operations

Let's say my bundle source looks something like this...

require('script-loader!polyfill.js')
require('app.js')

For the cases where polyfill.js is necessary, can I rely on it being called before anything in app.js?

  • webpack 4.17.2
  • script-loader 0.7.2

Allow script-loader to run more than once

Is it possible add a config or command to allow the script to load more than once in the same context ? It seems to only load once in the same context. Thanks in advance

CSP does not allow eval

Can we use another way other than calling eval?

This is not good for security reasons

https://github.com/webpack-contrib/script-loader/blob/master/addScript.js#L9

addScript.js:9 Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".


    at eval (<anonymous>)
    at e.exports (addScript.js:9)
    at Object.659 (jquery.mask.js?872b:1)
    at __webpack_require__ (bootstrap 3d71110…:54)
    at Object.869 (vendors.js:32296)
    at __webpack_require__ (bootstrap 3d71110…:54)
    at e.20 (bootstrap 3d71110…:152)
    at bootstrap 3d71110…:152

source: https://scotthelme.co.uk/content-security-policy-an-introduction/

Cannot find module "script-loader!./test.js"

require("script-loader!./test.js");

Console output:

app.js:4 Uncaught Error: Cannot find module "script-loader!./test.js"
at webpackMissingModule (app.js:4)

I have test.js in the same dir with the original script. I'm using Webpack 2.

Scripts not being executed

I'm trying to upgrade from webpack 1 to 2 . Everything compiles, loads just fine apparently, but globally required variables are not available.

The way I used to have it was, at some point in the entry flow, i had a lot of

require('!!script-loader!./vendor/file1.js')
require('!!script-loader!./vendor/file2.js')
require('!!script-loader!./vendor/file3.js')
// ...

this configuration worked just fine, but with the upgrade, it seems scripts are not being executed

The webpack configuration entries are two, core and vendor:

entry: {
      core: './app/javascripts/loader',
      vendor: [
        './app/javascripts/libraries',
        'backbone-redux',
        'brace-expansion'
      ]

If I put the require statements in the javascripts/loader file, it works (scripts are executed globally), but if I put them in javascripts/libraries files they don't.

Env:

  • webpack v2
  • webpack-dev-server v1.14
  • script-loader v0.7

Incorrect handling of `this` (should refer to `window`).

Hi,

Thanks for all your hard work. Some legacy scripts I'm trying to load use this to refer to window, eg; this.jQuery when a window-loaded jQuery is provided. However, I'm getting an uncaught TypeError, claiming this is undefined.

Note that I'm using the devtool eval-source-map, in case that could be related.

Thanks!

'use strict' defeats this loader?

require('!script!./findme.js')

findme.js

'use strict'

function Hello() {
  console.log( 'hello again' )
}

In chrome console

VM1968:1 Uncaught ReferenceError: Hello is not defined(…)

uncomment 'use strict'

// 'use strict'

function Hello() {
  console.log( 'hello again' )
}
Hello()
VM2146:5 hello again

Here are what the two versions look like in bundle

/* 624 */
/***/ function(module, exports) {

	module.exports = "\n'use strict'\n\nfunction Hello() {\n  console.log( 'hello again' )\n}\n"

/***/ },
/* 624 */
/***/ function(module, exports) {

	module.exports = "\n// 'use strict'\n\nfunction Hello() {\n  console.log( 'hello again' )\n}\n"

/***/ },

SourceMaps

I'm requiring a js file from my project, and I have devtools enabled with webpack. When I go to Chrome Devtools and I try to check the file, I only can see a compiled file like this:

module.exports = "[all-the-code]".

So... it's impossible to me to debug using devtools.

script-loader can not use in async require with angular(1.x.x)

My code :

  resolve: {
    lazyLoad: function($q){
      return $q(function(resolve, reject){
        require.ensure([], function(require){
          require('script!./modules/clusters/clusters.js');
          require('script!./vendor/galaxy-sdk-javascript/rpc/thrift.js');
          resolve()
        });
      })
    }
  }

Help

The script-load dose not support the async load? Anyone have the way to solve the problem? Thanks!

Help with script-loader and using in webpack config / es2015 imports ?

Hi,

I found the script-loader and got it working using the example given using require. I am actually using a webpack.config and ES2015

Can anyone confirm if I can use this with

  1. ES 2015 imports and how to do this?

  2. Using webpack.config and adding it to the loaders sections

There seems to be little documentation.

Its worth noting that i am using multiple script-loaders currently like so (using the nodejs require syntax)

require("script-loader!../lib/packer.js");
require("script-loader!../lib/decompress.js");
require("script-loader!../lib/consol.js");

An example for the 2 ways of doing this above would really helpful.

Thanks in advance

Compatibility with uglify plugin?

Is there a known issue with comments not being uglified out of modules being loaded with script-loader?

For instance, I have an entry file which looks like this...

// vendor.coffee
require("script!jquery/dist/jquery.min.js")
require("script!../assets/bootstrap/js/bootstrap.js")

...and a simplified version of my webpack config looks like this...

config =
  entry:
    vendor: "./vendor.coffee"
  plugins: [
    new webpack.optimize.UglifyJsPlugin({ output: {comments: false} }) // *
  ]

* using temporary solution for the structure of the comments output option from here

In this case, the resulting file still has a bunch of comments in it.

Am I missing something, or does uglify comment stripping just not work with files loaded with the script-loader? Are there other limitation when it comes to minification I should be aware of?

Thanks in advance for any help!

Error in IE7/8

require('script!../libs/parsleyjs/dist/parsley.min.js')
module.exports = function(src) {
    if (typeof execScript === "function")
        execScript(src);
    else
        eval.call(null, src);
}

eval.call(null, src) is not work in IE7/8

Including aws-sdk

Hi,
I'm trying to include a pre-built aws-sdk.js file into my bundle as a script.
My idea is to have a vendor dir which will contain all un-npm js, which I can just include with the script loader. This is instead of having <script tags in the index.html.
I'm not having much success ...
Dir :
webpack.config.js
node_modules/
vendor/aws-sdk.js
src/

webpack config

var webpack = require('webpack');
module.exports = {
  devtool: 'source-map',
  entry: [
    'webpack-dev-server/client?http://0.0.0.0:3000',
    'webpack/hot/only-dev-server',
    './src/index.js'
  ],
  output: {
    publicPath: '/',
    path: __dirname + '/build',
    filename: 'bundle.js'
  },
  resolve:{
    modulesDirectories : ["node_modules", "vendor"]
  },
  module: {
    preLoaders: [
      {test: /\.js$/, loader: "eslint-loader", exclude: /node_modules/}
    ],
    loaders: [

      {test: /aws-sdk\.js$/, loader: "script"},

      {test: /\.js?$/, loaders: ['react-hot', 'babel?stage=1'], exclude: /(node_modules|vendor)/},

      {test: /\.css$/, loader: "style!css"},
      {
        test: /\.(png|jpg)$/,
        loader: 'url?limit=25000'
      },
      {test: /\.woff$/, loader: "url?limit=50000"}
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ]
};

I'm not too sure what reggae I should use for the aws-sdk? if this should also have the vendor prefix or not? I'v tried both ..
Ideally I want all js in the vendor dir so something like .*vendor\/.*\.js$

Any help would be much appreciated,
Cheers,
Stephen.

Reference error when used with webpack-dev-server

I'm using script-loader to load some legacy scripts into my app. Everything works fine when I build with webpack, but when I build with webpack-dev-server instead (to enable hot reloading of other, non-legacy scripts in my project), all of my bundles that use script-loader throw an error in the browser;

[Script Loader] ReferenceError: require is not defined
...
at Object../node_modules/webpack-dev-server/client/index.js?http://localhost:8080 (myScriptLoaderBundle.js:338)

Oddly, the legacy scripts seem to still be loading in the browser, and the hot reloading of other resources works. But I'm trying to figure out what causes the error, and see if there's anything I can do to avoid it. I thought it might be related to liady/webpack-node-externals#17 but it doesn't look like script-loader uses webpack-node-externals.

Cannot use the script with Internet Explorer 11

Hello,

I can't use this script in InternetExplorer 11 on an Apache HTTP Server.

I get an error when calling the method execScript() from addScripts.js:

module.exports = function(src) {
if (typeof execScript !== "undefined")
execScript(src);
else
eval.call(null, src);
}

The execScript() method is deprecated in IE 11.

Any solutions to this ?

Using sourceMaps with script-loader

We are using script-loader to load pre minified files. These minified files usually also have source maps. script-loader should also specify where to find source maps.

Using script-loader seems to lead to a different `[chunkhash]` being generated each time

Hello,

First of all, I know that [chunkhash] is not the best idea for long term caching, and it's better to use a plugin that creates content-hash, which we will probably do very soon.
Nevertheless I wanted to report the issue, even if only to help some other people who are investigating similar issues.


So, we're using webpack 3.x for now, and we have two external scripts, let's call them foo and bar that are loaded through script-loader 0.7.1 like this:

  loadFooLib() {
    return import(/* webpackChunkName: 'foobar' */ 'script-loader!foo')
  },

(with foo$: 'html/vendor/foo/Foo' in webpack resolve config).

When we run the build twice after some time, without any code change in foo or bar (for example, a non-code commit), this often* results in the chunkhash change for foo and bar (the chunks that go through script-loader), and no output change for the other chunks -- and this in turn means that the manifest chunk has to be regenerated as well.

*often = not always, and it's happening a lot on our Linux build machines, but I could not reproduce so far on Windows

Looking at the code, things look very simple and there seems to be no obvious reason for script-loader to generate different chunkhash each time.

@sokra Do you have any ideas? Is this kind of issue more likely to be on the plugin side, or webpack side?

Evaluating works inconsistently among browsers

Please see the following blog post for explanation on why it is not possible to just run eval.call(null, src) and expect it to behave the same way in most of the browsers.

http://perfectionkills.com/global-eval-what-are-the-options/

It should be noted that even if the script written in that blog post is used, one should never rely 100% for this loader as it still might fail. Some kind of warning for unsupporting browsers could be given or maybe a plain-old script insertion should be done (if possible) for browsers which don't support indirect eval functionality nor execScript.

Error in IE 11

There is an error in IE11. The site doesn't work except when the dev toolbar is open. In that case I see and error: "[Script Loader] SyntaxError: Syntax error".

In my app.js file I'm using script-loader like this:

require('!!script-loader!./vendor/foo.js')
require('!!script-loader!jbar.js')

Any advice?

"require is not defined" when using with babel-loader

When I try to use script-loader after Babel I am getting a runtime error "require is not defined". This line is being added by Babel to all of the legacy files and is what is throwing the error:

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

Here is the relevant parts of my webpack config:

const _babelOptions = {
    babelrc: false,
    plugins: [
        '@babel/plugin-transform-modules-commonjs',
        [
            '@babel/plugin-transform-runtime', {
                corejs: 3,
                regenerator: true
            }
        ]
    ],
    presets: [
        [
            '@babel/preset-env', {
                useBuiltIns: 'entry',
                corejs: 3,
                targets: {
                    browsers: [
                        'firefox        >= 45',
                        'iOS            >= 10',
                        'chrome         >= 60',
                        'edge           >= 14',
                        'chromeandroid  >= 51', // android 7+

                        'not ie         >= 0',
                        'not android    >=  0'
                    ]
                }
            }
        ]
    ]
};
        rules: [
           {
                test: /\.js$/,
                include: /(Blackbox|confirmexit)/,
                exclude: /(node_modules)/,
                use: [
                    {
                        loader: 'script-loader',
                        options: {
                            useStrict: false
                        }
                    },
                    {
                        loader: 'babel-loader',
                        options: _babelOptions
                    }
                ]
            }
         ]

Please let me know if you need any other info.

Ability to minify raw files

script-loader uses raw-loader, so the require()'ed script does not undergo any processing.

It would be nice if the webpack --optimize-minimize would compress scripts loaded with script-loader.

I started toying with a 'minscript-loader' using uglify-js, which is pretty easy https://github.com/mishoo/UglifyJS2#the-simple-way
but I end up duplicating the code from script loader anyways, so there should be a better way.

Can't find module lib.js

I use script-loader for load non-module library. So I just try script-loader. But I can't load any .js files. While I load JS it throws error. Here are my example codes. What's wrong in my code?

// webpack.config.js
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist')
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: 'babel-preset-es2015'
                    }
                }
            },
            {
                test: /\.exec\.js$/, 
                use: {
                    loader: 'script-loader'
                }
             }
        ]
    }
}
// lib.js
function lib(){
    console.log('from lib.js')
}
// index.js
var lib = require('./lib.exe.js');
window.sample = lib;
console.log(lib);

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

Can't get it to work at all with webpack dev server

I tried loading 2 scripts one which uses a function defined in the other but it is always undefined. I tried in many places and using the debug I see the eval.call() and can step through the imported script but the values never stick. The Chrome tools indicate i'm in some sort of closure.

In case it helps here is my config - https://github.com/OpenDirective/brian/blob/master/webpack.config.js
And here are the scripts I tried to load - https://github.com/OpenDirective/brian/blob/master/src/assist.html . It's the second file that fails with BigInteger being undefined.

What does global context mean?

I would expect that this loader executes script myScript.js as if it was included with <script src="myScript.js">. This is not the case.

The following statement var myVar = {} will not add myVar as global (in contrast to how <script src="myScript.js"> behaves) . So in the html page: console.log(myVar) will print undefined.

Issue using script-loader in config, works inline.

Works fine when I do
import 'script-loader!../global/somescript.js';

I have lots of bundles that include lots of files.

I thought it would be better to just add the script loader to the config like so:

module: { rules: [ { test: /\.js$/, use: [ 'script-loader' ] } ] }

When I use this approach I get the following error:

[Script Loader] SyntaxError: Unexpected token import at eval (<anonymous>) at module.exports (addScript.js:20) at Object.<anonymous> (myscript.js?b969:1) at __webpack_require__ (bootstrap 4678668399b7e837c1db:19) at bootstrap 4678668399b7e837c1db:62 at bootstrap 4678668399b7e837c1db:62

Can any one help?

Not working with react-hot loader

require("script!./file.js");

Result in file.js:

Uncaught ReferenceError: module is not defined

File.js content after react-hot loader transformation:

/* REACT HOT LOADER */ if (module.hot) { (function () { var ReactHotAPI = require("D:\\Dev\\git\\React\\react-admin-example\\node_modules\\react-hot-loader\\node_modules\\react-hot-api\\modules\\index.js"), RootInstanceProvider = require("D:\\Dev\\git\\React\\react-admin-example\\node_modules\\react-hot-loader\\RootInstanceProvider.js"), ReactMount = require("react/lib/ReactMount"), React = require("react"); module.makeHot = module.hot.data ? module.hot.data.makeHot : ReactHotAPI(function () { return RootInstanceProvider.getRootInstances(ReactMount); }, React); })(); } (function () {

// FILE CONTENT

/* REACT HOT LOADER */ }).call(this); if (module.hot) { (function () { module.hot.dispose(function (data) { data.makeHot = module.makeHot; }); if (module.exports && module.makeHot) { var makeExportsHot = require("D:\\Dev\\git\\React\\react-admin-example\\node_modules\\react-hot-loader\\makeExportsHot.js"), foundReactClasses = false; if (makeExportsHot(module, require("react"))) { foundReactClasses = true; } var shouldAcceptModule = true && foundReactClasses; if (shouldAcceptModule) { module.hot.accept(function (err) { if (err) { console.error("Cannot not apply hot update to " + "file.js" + ": " + err.message); } }); } } })(); }

// SCRIPT-LOADER FOOTER

Seems to be having issues with source-maps

I have a little repo where im doing some testing to Webpack features.
One issue I haven't been able to solve is related source-maps for js files loaded using this webpack loader.

You can check the structure im describing next in the aforementioned repo, available at:
https://github.com/lmartins/WebpackBuildComponent

Webpack is processing the files like this

src/js/
   main.js - Entry point
   testeScriptLoader.js - Loaded with script-loader
   moduleA.js - Normal webpack require
   moduleB.js - Normal webpack require
   moduleC.js - Loaded using code splitting 

After setting up the project in Chrome Devtools and running Webpack, I get:
https://www.dropbox.com/s/2lo1ekw4xdzeuej/Screenshot%202014-05-31%2020.23.19.png

Every file seems to be accessible from devtools, meaning that I can click the source column edit and save the file, except for the file loaded using script-loader testeScriptLoader.js. For that file only, the source-map seems to be failing.

Any ideias?

Stable hashes

I'm using script-loader to inject some Foundation JS on our bundles and noticed that if I change the path where the repository is, the contenthash changes, this completely broke our deployment pipeline as the assets are generated more than once for different distribution places and the hashes ended up being different.

Try it yourselves at https://github.com/gforcada/webpack-stable-hashes

The solution I found myself is move the import to the JS file rather than at the webpack configuration like this:

app.js
require('foundation-sites/path/to/file.js');

webpack.js

module.exports = {
  entry: {
    app: './app.js'
  },
  ...

Might be something worth mentioning on the README? 🤔

Our webpack configuration is quite complex and it took me a complete morning to pin it down to this specific lines (we have several lines like '!!script-loader!foundation-sites/dist/plugins/foundation.core.js', on our webpack configuration).

Error: require is not defined

This seems like a problem I shouldn't be having, but that's the error I keep running into with this loader. I've added a stripped-down config and the generated bundle in this gist, and it's easy to see that the call to require for each module is going to fail.

My situation: I have a bunch of legacy JS (no modules, expecting to run in window) that just needs to be bundled in the correct order and minified. Nothing else. All I need is for the scripts to be loaded in the page like so:

<script src="manifest.js"></script>
<script src="legacyJS.[hash].js"></script>

Correct me if I'm wrong, but this loader seems like the answer to this problem. How can I make the require function get passed to each module in the output? It looks like the output isn't fully evaluated or something, since I want the contents of those files passed through the loaders, not the string of loaders+filepath. I see in the brief example in the readme that the generated modules are still meant to be imported, but I don't want that here. What am I doing wrong? Am I so confused that this loader isn't the one I want?

Many thanks.

Better example for new webpack folk

The useage example is probably enough for webpack experts. But it would be nice to know where in the config file that require statement is supposed to go. (Just a suggestion.)

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.