How to use Webpack loaders syntax ( imports/export

2019-07-15 09:10发布

问题:

I'm using Webpack and Babel to build an Angular1.4 project, written in ECMA6 syntax. I'd like to use ECMAScript 6 import/export default module syntax, but sometimes I have to use Webpack loaders, such as expose to globally expose modules (e.g. jquery, required to be a global object by angular): require("expose?jquery!jquery").

Is there a way to write ECMAScript6 imports with Webpack loaders? Something like:

import "expose?jquery!jquery"

I can't mix require() calls with import calls, because imports hoist to the top of the module and break the order of dependency loading. E.g.

require("expose?jquery!jquery);
import angular from "angular";

transpiles to:

var angular = require("angular");
require("expose?jquery!jquery);

which breaks the build, because window.jquery is required by my Angular directives that expect angular.element to be full jquery, not angular's jqLite.

And require breaks with modules, exported with exports default.

回答1:

Why don't you give Webpack's Provide plugin a shot?

In your webpack.config.js:

var webpack = require('webpack'); 
// Remember to install webpack locally with `npm install webpack`

module.exports = {
    ...
    plugins: [
        new webpack.ProvidePlugin({
            jQuery: 'jquery'
        })
    ],
    ...
}

This way you'll have jQuery as a global throughout your project without having to manually require it!

Edit: I use jQuery with the uppercase Q, you are of course free to use it all lowercase. You should also be able to use both!

Edit 2: Another thing worth noting is that it's not that Webpack breaks with require and export default, it's that Babel has actually fixed a misconception in version 6: if you want to use require with an ES6/7 module you have to require the default export, so require('myModule').default. In general, you should only use require with CommonJS modules, while you can use import with (almost) everything.