星期一, 11月 28, 2016

[Webpack] 解決jquery在webpack載入全域的處理方法

webpack真是個很屌但不熟會搞死人的東西,
為了搞一個全域的jquery函式庫,
找到StackFlow裡面一個大神提供的各種解法

這位大大也有遇到一樣的事:D
https://blog.fntsr.tw/articles/2016/09/13/%E8%AE%93-jquery-%E5%9C%A8-webpack-%E4%B8%AD%E6%88%90%E7%82%BA%E5%85%A8%E5%9F%9F%E8%AE%8A%E6%95%B8/

備份文章





351
down voteaccepted
You've mixed different approaches how to include legacy vendor modules. This is how I'd tackle it:

1. Prefer unminified CommonJS/AMD over dist

Most modules link the dist version in the main field of their package.json. While this is useful for most developers, for webpack it is better to alias the src version because this way webpack is able to optimize dependencies better (e.g. when using the DedupePlugin).
// webpack.config.js

module.exports = {
    ...
    resolve: {
        alias: {
            jquery: "jquery/src/jquery"
        }
    }
};
However, in most cases the dist version works just fine as well.

2. Use the ProvidePlugin to inject implicit globals

Most legacy modules rely on the presence of specific globals, like jQuery plugins do on $ or jQuery. In this scenario you can configure webpack, to prepend var $ = require("jquery")everytime it encounters the global $ identifier.
var webpack = require("webpack");

    ...

    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]

3. Use the imports-loader to configure this

Some legacy modules rely on this being the window object. This becomes a problem when the module is executed in a CommonJS context where this equals module.exports. In this case you can override this with the imports-loader.
Run npm i imports-loader --save-dev and then
module: {
    loaders: [
        {
            test: /[\/\\]node_modules[\/\\]some-module[\/\\]index\.js$/,
            loader: "imports?this=>window"
        }
    ]
}
The imports-loader can also be used to manually inject variables of all kinds. But most of the time the ProvidePlugin is more useful when it comes to implicit globals.

4. Use the imports-loader to disable AMD

There are modules that support different module styles, like AMD, CommonJS and legacy. However, most of the time they first check for define and then use some quirky code to export properties. In these cases, it could help to force the CommonJS path by setting define = false.
module: {
    loaders: [
        {
            test: /[\/\\]node_modules[\/\\]some-module[\/\\]index\.js$/,
            loader: "imports?define=>false"
        }
    ]
}

5. Use the script-loader to globally import scripts

If you don't care about global variables and just want legacy scripts to work, you can also use the script-loader. It executes the module in a global context, just as if you had included them via the 

沒有留言:

張貼留言

留個話吧:)