GithubHelp home page GithubHelp logo

peerigon / modernizr-loader Goto Github PK

View Code? Open in Web Editor NEW
163.0 15.0 19.0 59 KB

Get your modernizr build bundled with webpack

License: MIT License

JavaScript 100.00%
modernizr webpack modernizr-loader

modernizr-loader's Introduction

modernizr-loader for webpack

Build Status devDependency Status peerDependency Status

Installation

$ npm install --save-dev modernizr modernizr-loader json-loader

Initialization

You have to create a .modernizrrc configuration file and put your modernizr stuff in it. Like so

// .modernizrrc
{
  "minify": true,
  "options": [
    "setClasses"
  ],
  "feature-detects": []
}

Full list of supported "options" and "feature-detects" can be found in Modernizr config-all.json.

Webpack config

Documentation: Using loaders

Put the following code to your webpack config file:

const path = require('path');

module.exports = {
  module: {
    rules: [
      {
        test: /\.modernizrrc.js$/,
        use: [ 'modernizr-loader' ]
      },
      {
        test: /\.modernizrrc(\.json)?$/,
        use: [ 'modernizr-loader', 'json-loader' ]
      }
    ]
  },
  resolve: {
    alias: {
      modernizr$: path.resolve(__dirname, "path/to/.modernizrrc")
    }
  }
}

Usage

Now you are able to import your custom Modernizr build as a module throughout your application like so:

import Modernizr from 'modernizr';

if (!Modernizr.promises) {
    // ...
}

See the Modernizr documentation for all available options.

Contribution

Don't hesitate to create a pull request. Every contribution is appreciated.

Sponsors

modernizr-loader's People

Contributors

clessg avatar danilobuerger avatar evilebottnawi avatar flootr avatar greengremlin avatar jhnns avatar jmarceli avatar meaku avatar samtsai avatar skyrpex 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

modernizr-loader's Issues

Build errors: dependencies not found

I'm trying to make the switch from a grunt development environment to webpack. So far it hasn't been easy, but Modernizr and this loader have been giving me a headache for two days now..

I tried several different modernizr version and loaders, but no luck....
As you can see I followed everything from the read.me but I keep getting the same errors..
The modernizr in /node_modules has a package.json file, but when I run npm install in this folder, none of the grunt plugins get installed, so theres no way I can build a custom file...
I'm really getting frustrated here, so any help would be appreciated.

`
ERROR Failed to compile with 6 errors 16:43:55

These dependencies were not found:

  • fs in ./node_modules/modernizr/lib/metadata.js, ./node_modules/modernizr/lib/options.js and 2 others
  • generate in ./node_modules/modernizr/lib/build.js
  • lib/generate-banner in ./node_modules/modernizr/lib/build.js

To install them, you can run: npm install --save fs generate lib/generate-banner
`

However when I try to install these I get errors these repo's don't even exist anymore?

My webpack.config.js:

`const path = require('path');
const Encore = require('@symfony/webpack-encore');
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const devMode = process.env.NODE_ENV !== 'production';
const glob = require("glob");

Encore
// the project directory where compiled assets will be stored
.setOutputPath('public/build/')
// the public path used by the web server to access the previous directory
.setPublicPath('/build')
.enableSourceMaps(!Encore.isProduction())
.enableSassLoader()
.enablePostCssLoader((options) => {
options.config = {
path: 'config/postcss.config.js'
};
})
.autoProvideVariables({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
})
.enableVueLoader()
.enableVersioning()
.cleanupOutputBeforeBuild()
.addEntry('js/app', './assets/js/app.js')
.addStyleEntry('css/app', ['./assets/scss/app.scss'])
.addEntry('img', glob.sync('./assets/img/*'))
.splitEntryChunks()
.enableSingleRuntimeChunk();

module.exports = {
module: {
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
})
]
},
rules: [{
test: /.js$/,
exclude: /(node_modules|bower_components)/,
use: [{
loader: 'babel-loader',
options: {
presets: ['env'],
},
}, {
loader: 'eslint-loader',
options: {
failOnError: true,
},
}]
},
{
test: /.scss$/,
use: [{
loader: MiniCssExtractPlugin.loader,
},
'style-loader',
"css-loader",
'postcss-loader',
'sass-loader',
OptimizeCssAssetsPlugin.loader
]
},
{
test: /.(gif|png|jpe?g|svg)$/i,
use: [
'file-loader',
{
loader: 'url-loader',
options: {
limit: 8000
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 6
},
optipng: {
enabled: true,
},
pngquant: {
quality: '65-90',
speed: 4
},
gifsicle: {
interlaced: false,
},
// the webp option will enable WEBP
webp: {
quality: 75
}
}
}
]
},
{
test: /.modernizrrc.js$/,
use: [ 'modernizr-loader' ]
},
],
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /.css$/,
cssProcessor: require('cssnano'),
cssProcessorOptions: {
safe: true,
discardComments: {
removeAll: true
}
},
canPrint: true
})
]
},
resolve: {
alias: {
modernizr$: path.resolve(__dirname, ".modernizrrc")
}
},
stats: {
colors: true,
}
};

module.exports = Encore.getWebpackConfig();
`

.modernizrrc file:

{ "minify": true, "options": [ "domPrefixes", "prefixes", "addTest", "atRule", "hasEvent", "mq", "prefixed", "prefixedCSS", "prefixedCSSValue", "testAllProps", "testProp", "testStyles", "html5shiv", "setClasses" ], "feature-detects": [ "test/ambientlight", "test/applicationcache", "test/audio", "test/battery", "test/blob", "test/canvas", "test/canvastext", "test/contenteditable", "test/contextmenu", "test/cookies", "test/cors", ] }

json-loader is not required for webpack v2 and above

The documentation for this loader instructs you to install json-loader, but for users on webpack 2 and above, it is not required. This is one of the first lines in json-loader:

โš ๏ธ Since webpack >= v2.0.0, importing of JSON files will work by default. You might still want to use this if you use a custom file extension. See the v1.0.0 -> v2.0.0 Migration Guide for more information

cacheable

Is there a reason this loader does not opt in to being cacheable?

Uncaught TypeError: _modernizr2.default.mq is not a function

I'm using the exact configuration as specified in the Readme, and the import of Modernizr works.

However, when I go to use the thing, I get the error Uncaught TypeError: _modernizr2.default.mq is not a function.

Here is my modernizr config:

{
  "minify": true,
  "options": [
    "setClasses",
    "mq"
  ],
  "feature-detects": []
}

When I use mq, I get the error above. Here is my code:

import Modernizr from 'modernizr'
...
var query = Modernizr.mq('screen and (max-width: 600px)')

Incidentally, if I print out the Modernizr object, I get this:

{
  "minify":true,
  "options": ["setClasses","mq"],
  "feature-detects":[]
}

Where it's quite obvious that mq is not even a direct descendant, let alone a function.

However, this is what the docs say to do, so what gives?

readme fix

shouldn't it be require("!modernizr!/.modernizrrc")(with an !) instead of require("!modernizr./.modernizrrc")(with a .)?

specific chunk

Hi,

I have a requirement from a front-end dev to place the modernizr package in the head of our application. This is due to the fact that the view will get a flicker if the modernizr javascript loads AFTER CSS classes that use modernizr classes.

How would one go about making the modernizr builder an entry? Could it be chunked on the output?

I would need the custom modernizr build to be chunked, but the resulting output being a global file that can be referenced within the components that use the Modernizr JS.

Thoughts... does this make sense and is possible?

Thanks!

Cannot resolve module .modernizrrc with webpack config

I couldn't make it work. All three files in the same directory.

webpack.config.js:

// @flow

var path = require("path");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var poststylus = require('poststylus');
var cssnext = require('postcss-cssnext');

module.exports = {
  entry: {
    home: "./app.jsx"
  },
  output: {
    path: path.resolve(__dirname,'dist'),
    recordsPath: path.resolve(__dirname, 'dist'),
    filename: "[name].js",
    chunkFilename: "[id].js"
  },
  module: {
    loaders: [
      {
        test: /\.jsx$/, exclude: /node_modules/,
        loader: "babel-loader"
      },
      {
        test:/\.modernizrrc$/,
        loader: "modernizr"
      },
      {
        test: /\.styl$/, exclude: /node_modules/,
        loader: ExtractTextPlugin.extract(
          "style-loader",
          "css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!stylus-loader"
        )
      },
      {
        test: /\.(png|jpg)$/, exclude: /node_modules/,
        loader: 'file-loader?name=assets/images/[name].[ext]',
      },
      {
        test:/\.(ttf|eot|svg|woff|woff2)$/, exclude: /node_modules/,
        loader: "file-loader?name=assets/fonts/[hash:base64:5].[ext]"
      }
    ]
  },
  stylus: {
    use: [
      poststylus([
        cssnext({ 'browsers':'ie 6-8' })
      ])
    ]
  },
  plugins: [
    new ExtractTextPlugin("[name].css")
  ],
  resolve: {
    alias: {
      modernizr$: path.resolve(__dirname, ".modernizrrc")
    }
  },
  devServer: {
    stats: 'errors-only'
  }
};

app.jsx:

// @flow

import React from 'react'
import ReactDOM from 'react-dom'

//import Modernizr from 'modernizr'
require('.modernizrrc');

import styl from './styl/home.styl'

var App = React.createClass({
  render: function() {
    return (
      <div className={styl.test}>
        Hello universe...
      </div>
    )
  }
})

ReactDOM.render(
  <App />,
  document.getElementById('root')
)

.modernizrrc:

{
  "minify": true,
  "options": [
    "setClasses"
  ],
  "feature-detects": [
    "serviceworker",
    "svg",
    "picture",
    "promises"
  ]
}

Is this project deprecated?

Hasn't been updated in a couple of years and lots of issues popping up regarding official Webpack 4 support.

Improve documentation

Hi,
This is really useful project thanks for that. Anyway I would like to suggest some README improvements:

If you like this suggestions I may send a PR.

Config from readme gives "path is not defined"

Specifically, this line:

$ gulp
webpack.config.js:31
            modernizr$: path.resolve(__dirname, ".modernizrrc")
                        ^

ReferenceError: path is not defined
    at Object.<anonymous> (webpack.config.js:31:25)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (gulpfile.js:63:23)
    at Module._compile (module.js:570:32)

Do I need to add an import/require? If so, perhaps this could be included in the readme as well.

SyntaxError: Unexpected token :

So I'm getting a weird error, and I'm hoping someone can help me out. I'm a bit new to Webpack -- this is a rails app -- (though I'm a fairly advanced coder) so I could be doing something dumb.

The error is as follows

ERROR in ./app/javascript/modernizrrc.json
Module build failed: [PRIVATE]/app/javascript/modernizrrc.json:2
  "classPrefix": "",
               ^

SyntaxError: Unexpected token :
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.exec ([PRIVATE]/node_modules/webpack/lib/NormalModule.js:129:12)
    at Object.module.exports ([PRIVATE]/node_modules/modernizr-loader/index.js:24:26)
 @ ./app/javascript/packs/coming_soon.js 4:0-44
 @ multi (webpack)-dev-server/client?http://localhost:3035 ./app/javascript/packs/coming_soon.js

This makes no sense though, because (to my reading) this is a parser error regarding the the JSON config file, but I actually obtained the file directly from the Modernizr GitHub repo by running

curl https://raw.githubusercontent.com/Modernizr/Modernizr/v3.5.0/lib/config-all.json > modernizrrc.json

For what it's worth, here's the config I'm using for my webpacker environment setup:

const path = require('path');

module.exports = {
  module: {
    rules: [
      {
        test: /\.?modernizrrc(\.js(on)?)?$/,
        use: [ 'modernizr-loader' ]
      }
    ]
  },
  resolve: {
    alias: {
      'modernizr$': path.resolve(__dirname, "../../../app/javascript/modernizrrc.json")
    }
  }
}

Any ideas?

Dependency not found

I'm using this with Modernizr and Nuxt but I get an error during compilation.

.modernizrrc file

{
  "minify": true,
  "options": [
    "addTest",
    "setClasses"
  ],
  "feature-detects": [
    "test/audio",
    "test/video",
    "test/audio/webaudio",
    "test/webrtc/getusermedia"
  ]
}

nuxt.config.js file

// Other code
...
build: {
    extend(config, { isDev, isClient }) {
      config.module.rules.push(
        {
          test: /\.modernizrrc.js$/,
          loader: "modernizr"
        },
        {
          test: /\.modernizrrc(\.json)?$/,
          loader: "modernizr!json"
        }
      ),
      config.resolve.alias['modernizr$'] = path.resolve(__dirname, "~/.modernizrrc")
    }
  },
....

The error

This dependency was not found:

* modernizr in ./node_modules/babel-loader/lib??ref--14-0!./node_modules/ts-loader??ref--14-1!./node_modules/@nuxt/components/dist/loader.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./components/landing/Intro.vue?vue&type=script&lang=ts&

To install it, you can run: npm install --save modernizr

I already have it installed so I'm not sure what's the error.

"modernizr": "^3.11.3",
"modernizr-loader": "^1.0.1",

Saw someone else commented on a StackOverflow post that its becausevue-loader doesn't "like" modernizr-loader? Any help would be greatly appreciated.

Pleas update npm docs!

Specifically the webpack config. The link to the webpack loader documentation is dead and the loaders code is outdate.

Docs on github work great. Thanks for the awesome work otherwise!

detection of keyframes does not work

When I add the following code to my javascript file...


"use strict";
import Modernizr from 'modernizr';

....

var keyframes = Modernizr.atRule('@keyframes');
if (keyframes) {
console.log(' Yes, keyframes are supported. It could be @-webkit-keyframes or @keyframes');
} else {
console.log('keyframes are not supported');
}

Chrome tells me in the console...

Uncaught TypeError: modernizr__WEBPACK_IMPORTED_MODULE_0___default.a.atRule is not a function

The modernizr-loader does not work with karma-webpack

When try to use karma-webpack to run jasmine tests, with the same loaders as dev/prod, it throws error

ERROR in ./.modernizrrc
Module parse failed: C:\PathToRoot\.modernizrrc Unexpected token (2:12)
You may need an appropriate loader to handle this file type.

The other tests (for modules do not require modernizr) runs fine.

Errors with Webpack build

I'm having difficulties getting modernizr-loader setup. I followed the README, but unfortunately hit a lot of errors anytime I attempt to import Modernizr from 'modernizr'. Any thoughts as to what is going on here? Thanks!

Errors

Full list of errors

ERROR in ./~/modernizr/lib/build.js
Module not found: Error: Cannot resolve module 'generate' in /Users/username/Sites/web/gn-join/node_modules/modernizr/lib
 @ ./~/modernizr/lib/build.js 151:2-72

[...]

Config

// webpack.config.js
var path = require('path')

module.exports = {
  entry: path.join(__dirname,'./src/index.js'),

  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: 'assets'
  },

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
      { test: /\.json$/, loader: 'json' },
      { test: /\.modernizrrc$/, loader: 'modernizr'}
    ]
  },

  resolve: {
    modernizr$: path.resolve(__dirname, '.modernizrrc')
  }
}
# .modernizrrc
{
  "minify": true,
  "options": [
    "setClasses"
  ],
  "feature-detects": [
    "test/touchevents"
  ]
}

Peer Dependency Versions

Instructions don't work using webpack 2.2.0

Using config as on readme (an .modernizrrc file as json) and importing Modernizr I get an error indicating the loader is not a loader. The file path in the log seems to indicate it's finding the Modernizr package and not the loader at all.

/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/loader-runner/lib/loadLoader.js:35
                        throw new Error("Module '" + loader.path + "' is not a loader (must have normal or pitch function)");
                        ^

Error: Module '/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/im-fabric/node_modules/modernizr/lib/cli.js' is not a loader (must have normal or pitch function)
    at loadLoader (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/loader-runner/lib/loadLoader.js:35:10)
    at iteratePitchingLoaders (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/loader-runner/lib/LoaderRunner.js:164:2)
    at runLoaders (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/loader-runner/lib/LoaderRunner.js:357:2)
    at NormalModule.doBuild (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/webpack/lib/NormalModule.js:129:2)
    at NormalModule.build (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/webpack/lib/NormalModule.js:180:15)
    at Compilation.buildModule (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/webpack/lib/Compilation.js:127:10)
    at factoryCallback (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/webpack/lib/Compilation.js:304:11)
    at /Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/webpack/lib/NormalModuleFactory.js:242:4
    at /Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/webpack/lib/NormalModuleFactory.js:93:13
    at /Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/tapable/lib/Tapable.js:204:11

If I change loader config to modernizr-loader I get a different error -

[16:07:34] ./.modernizrrc
Module build failed: /Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/im-fabric/.modernizrrc:2
  "minify": true,
          ^
SyntaxError: Unexpected token :
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.exec (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/webpack/lib/NormalModule.js:98:6)
    at Object.module.exports (/Users/steve.gibbings/WebstormProjects/wcp-core/wordpress/themes/node_modules/modernizr-loader/index.js:24:26)
 @ ./src/js/view-model/common-vm.js 10:0-34
 @ ./src/js/entry.js
 @ multi ./src/js/polyfills/polyfills.js ./src/js/entry

Support `config` through `query`

Use:

import Modernizr from 'modernizr';

And in webpack in loaders:

{
    loader: 'modernizr?config=' + JSON.stringify(config.get('modernizr')),
    test: /modernizr.js$/
}

I can do PR if you have not time for this ๐Ÿ˜„

Module build failed

I am getting this error:

ERROR in ./conf/.modernizrrc
Module build failed: SyntaxError: Unexpected token :
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Object.loaderContext.exec (/home/vshadaka/personal_html/archer/node_modules/webpack/lib/NormalModule.js:94:6)
    at Object.module.exports (/home/vshadaka/personal_html/archer/node_modules/modernizr-loader/index.js:24:26)
 @ ./src/index.js 9:0-20

My Conf modernizrrc file is:

{
  "minify": true,
  "options": [
    "domPrefixes",
    "hasEvent",
    "testAllProps",
    "testProp",
    "html5shiv",
    "setClasses"
  ],
  "feature-detects": [
    "test/history",
    "test/postmessage",
    "test/svg",
    "test/a/download",
    "test/css/transitions",
    "test/file/api",
    "test/storage/localstorage",
    "test/svg/inline"
  ]
}

Webpack Version is 2.1.0-beta.20

modernizr-loader does not work with json5-loader@4

It seems that modernizr-loader does not work with json5-loader@4 (it works for json5-loader@3 and below). I get the following error:

path\to\.modernizrrc:1
(function (exports, require, module, __filename, __dirname) { export default {minify:true,options:['setClasses'],'feature-detects':['css/transformstylepreserve3d','css/transitions']}
                                                              ^^^^^^
SyntaxError: Unexpected token export

Tests

Where are the tests that i can run with npm test (according to the README) ?

Isomorphic / SSR Issue

Modernizr throws: window is not defined on server (React/SSR)

any ideas on how to work around that in webpack/React/SSR environment?

Still getting "ReferenceError: document [/window] is not defined"

I'd love to use this module, but it fails on build (es6/babel/webpack/yarn):

Error: ./.modernizrrc
Module build failed: ReferenceError: document is not defined
    at /Users/fabioa/Development/projects/mfsjs/.modernizrrc:4:1876
    at Object.<anonymous> (/Users/fabioa/Development/projects/mfsjs/.modernizrrc:6:3)
    at Module._compile (module.js:571:32)
    at Object.exec (/Users/fabioa/Development/projects/mfsjs/node_modules/webpack-core/lib/NormalModuleMixin.js:88:7)
    at Object.module.exports (/Users/fabioa/Development/projects/mfsjs/node_modules/modernizr-loader/index.js:20:26)

I took a look at merge request #25 but even after implementing it I still got the same error.

Any ideas on how to fix this? Should I be including jsdom somewhere?

If I include #25 and

modulesDirectories: [
      'node_modules',
      'bower_components',
    ],

I get

Error: ./.modernizrrc
Module build failed: ReferenceError: window is not defined
    at Object.<anonymous> (/Users/fabioa/Development/projects/mfsjs/.modernizrrc:10:4)
    at Module._compile (module.js:571:32)
    at Object.exec (/Users/fabioa/Development/projects/mfsjs/node_modules/webpack-core/lib/NormalModuleMixin.js:88:7)
    at Object.module.exports (/Users/fabioa/Development/projects/mfsjs/node_modules/modernizr-loader/index.js:24:26)

Error in webpack Build

I am followed the steps as per the readme file and Got the same issue as the issue-5 ( #5 )

As mentioned by @flootr, I have updated the code but No Luck

Webpack: v2.1.0-beta.20

Let me know if you need any more information

Error when parsing modernizrrc

When I followed your readme I received following error:

ERROR in ./.modernizrrc
Module build failed: ...\app\.modernizrrc:2
  "minify": true,
          ^
SyntaxError: Unexpected token :
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.exec (...\app\node_modules\webpack\lib\NormalModule.js:126:12)
    at Object.module.exports (...\app\node_modules\modernizr-loader\index.js:24:26)

My .modernizrrc :

{
  "minify": true,
  "options": [
    "setClasses"
  ],
  "feature-detects": [
    "serviceworker",
    "svg",
    "picture",
    "promises"
  ]
}

And packages used

"modernizr": "3.5.0",
"modernizr-loader": "1.0.1",
"webpack": "2.5.0",

[Docs] Installing modernizr package

A bit nitpicky, but in README is described how to install the dependencies:

$ npm install --save-dev modernizr modernizr-loader json-loader

modernizr package is installed as a dev dependency, however, it is actually used in the bundle, so shouldn't it be rather a normal dependency? So that it has to be installed in a second step like this?:

$ npm install --save-dev modernizr-loader json-loader
$ npm install modernizr

How to use it with Babel ES6?

Hi,
I'm using this loader along with babel es6 transpilation and I can't get it to work as I expect. This is how I use it now:

require("!modernizr!../../../.modernizrrc");

import $ from 'jquery';

export default class FlexboxFix {
  constructor() {
    if (!window.Modernizr.flexbox || !window.Modernizr.flexwrap) {
      this.noFlexbox();
    }
  }

  noFlexbox() {
    $('.SectionWrapper').wrapInner('<div class="IE-SectionWrapper"></div>');
  }
}

And that is my expected way of using (which doen't work and produces errors about resolving module 'fs':

// require("!modernizr!../../../.modernizrrc"); // requiring before import doesn't help

import $ from 'jquery';
import Modernizr from 'modernizr'; // this line produces errors like: Module not found: Error: Cannot resolve module 'fs' ... modernizr/lib

export default class FlexboxFix {
  constructor() {
    if (!Modernizr.flexbox || !Modernizr.flexwrap) {
      this.noFlexbox();
    }
  }

  noFlexbox() {
    $('.SectionWrapper').wrapInner('<div class="IE-SectionWrapper"></div>');
  }
}

modernizr package is required

It looks like proper README installation command should be:

$ npm install --save-dev modernizr modernizr-loader

As the modernizr is required to generate final bundle or am I missing something?

After update to 1.0.0 detects are incorrect

After the update from 0.5 some feature detects are incorrect, for example with a project in 0.5 the feature detect "eventlistener" returns true on the latest version of Chrome, with 1.0.0 it returns false.

Compatibility with modernizr-server

Hi,

I just made some middleware to handle fetching modernizr information to the server. It's called modernizr-server. Do you think its possible to change the wrapOutput function while targetting node to something like this? Not to experience with building webpack loaders.

function wrapOutput(output) {
    // Exposing Modernizr as a module.
    return ";(function(global){\n" +
         "var hadGlobal = 'Modernizr' in global;\n" +
         "var oldGlobal = global.Modernizr;\n" +
         "global.Modernizr = `" + output + "`\n" +
         "module.exports = global.Modernizr;\n" +
         "if (hadGlobal) { global.Modernizr = oldGlobal; }\n" +
         "else { delete global.Modernizr; }\n" +
    "})(global);";
}

This would just make expose the modernizr build as a string that modernizr-server would send to the client to be executed.

It would work with modernizr-server like this.

app.use(modernizrServer({
  build: Modernizr
}))

app.get('/', function(req, res) {
  let Moderizr = req.cookies.modernizr
}

see modernizr-server for more information.

"You may need an appropriate loader to handle this file type."

Hi everyone,

I've spent the last couple of hours trying to add Modernizr to my webpack 2 setup but I wasn't able to solve this error:
Module not found: Error: Can't resolve 'modernizr' in .../Webpack2Setup/src/js/main.js

.../Webpack2Setup/package.json

...
"devDependencies": {
  ...
  "modernizr": "^3.3.1",
  "modernizr-loader": "^1.0.1",
  ...
},
...

.../Webpack2Setup/webpack.config.js

var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HTMLWebpackPlugin = require('html-webpack-plugin');

const PRODUCTION = process.env.NODE_ENV === 'production';
const DEVELOPMENT = process.env.NODE_ENV === 'development';

var entry = PRODUCTION
  ? ['./src/js/main.js']
  : [
      './src/js/main.js',
      'webpack/hot/dev-server',
      'webpack-dev-server/client?http://localhost:8080'
    ];

var plugins = PRODUCTION
  ? [
      new webpack.optimize.UglifyJsPlugin(),
      new ExtractTextPlugin('style-[contenthash:10].min.css'),
      new HTMLWebpackPlugin({
        template: 'index-template.html'
      })
    ]
  : [
      new webpack.HotModuleReplacementPlugin()
    ];

plugins.push(
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(PRODUCTION),
    DEVELOPMENT: JSON.stringify(DEVELOPMENT)
  })
);

const scssIdentifier = PRODUCTION ? '[hash:base24:10]' : '[path][name]---[local]';

// Loaders are read from right to left
const scssLoader = PRODUCTION
  ? ExtractTextPlugin.extract({
      loader: ['css-loader?minimize&importLoaders=1', 'postcss-loader', 'sass-loader?localIdentName=' + scssIdentifier]
    })
  : ['style-loader', 'css-loader?importLoaders=1', 'postcss-loader', 'sass-loader?localIdentName=' + scssIdentifier];

module.exports = {
  externals: {
    'jquery': 'jQuery'
  },
  devtool: DEVELOPMENT ? 'source-map' : false,
  entry: entry,
  plugins: plugins,
  module: {
    rules: [
      {
        test: /\.js$/,
        enforce: "pre",
        loader: "eslint-loader"
      },
      {
        test: /\.modernizrrc.js$/,
        loader: "modernizr"
      },
      {
        test: /\.js$/,
        use: ['babel-loader'],
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: ['url-loader?limit=10000&name=images/[hash:12].[ext]'],
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
        use: scssLoader,
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    alias: {
      modernizr$: __dirname + "./.modernizrrc"
    }
  },
  output: {
    path: __dirname + '/dist',
    publicPath: PRODUCTION ? '/' : '/dist/',
    filename: PRODUCTION ? 'bundle.[hash:12].min.js' : 'bundle.js'
  }
};

.../Webpack2Setup/.modernizrrc

{
  "minify": false,
  "options": [
    "setClasses"
  ],
  "feature-detects": [
    "test/css/flexbox",
    "test/es6/promises",
    "test/serviceworker"
  ]
}

.../Webpack2Setup/src/js/main.js

...
import Modernizr from 'modernizr';
...

There's something missing? If you need to take a look at the complete repo, you can find it here (without Modernizr).

Thank you in advance

Not working with webpack@^5.0.0

The new webpack version is not compatible with this loader, the compiler throws

ERROR in ./app/vendor/modernizrrc.json
Module build failed (from ../node_modules/modernizr-loader/index.js):
TypeError: this.exec is not a function
    at Object.module.exports (/Users/user/project/node_modules/modernizr-loader/index.js:24:26)
 @ ./app/vendor/modernizr-custom.js 2:0-33 2:1372-1389 2:1442-1459 2:1516-1533 2:1586-1603 2:1610-1624 2:1626-1640 2:1642-1658 2:1660-1677

Any idea why?

Installation process clarification

Hi!

Small clarification. Do users really need to do npm install --save modernizr-loader, wouldn't it be better to use --save-dev flag, since it is a common practice to put loaders to devDependecies.

What do you think about that? ๐Ÿ’ญ

No Such File or Directory

ENV: OSX 10.11.6
WebPack: 4.8.3
Modernizr: 3.6.0
Modernizr-Loader: 1.0.1

.modernizrrc

{
  "minify": true,
  "options": [
    "domPrefixes",
    "hasEvent",
    "testAllProps",
    "testProp",
    "html5shiv",
    "setClasses"
  ],
  "feature-detects": [
    "contenteditable",
    "customelements",
    "customevent",
    "history",
    "indexeddb",
    "indexeddbblob",
    "serviceworker",
    "flexbox",
    "fetch",
    "localstorage",
    "sessionstorage",
    "svgasimg",
    "inlinesvg"
  ]
}

webpack.config.js

resolve: {
    alias: {
      modernizr$: path.resolve(__dirname, "../.modernizrrc")
    },
  }

module: {
    rules: [
      {
        test: /\.modernizrrc$/,
        use: [ 'modernizr-loader', 'json-loader' ]
      },
    ]
}

Webpack appears to be correctly parsing its config and .modernizrrc but throws the following:

screen shot 2018-07-18 at 9 43 18 am

Any ideas what I am doing wrong? Thank you very much in advance!

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.