前端 - webpack如何打包script标签引入的代码
阿神
阿神 2017-04-17 16:37:13
0
3
521

比如我的库文件vue,vuex 这些都是通过cdn 使用script加载到html,那我在打包的时候 就不会去打包库文件,而是使用我的script的资源。那我源码里面就不能使用require('vue') 这种代码。这个应该如何解决

阿神
阿神

闭关修行中......

reply all(3)
迷茫

First, you need to determine the module specifications supported by the bundle file you package. I prefer umd, so the bundle files I package are all umd. In other words, it supports commjs, amd and global module forms. Fortunately, the package released by vue is also umd, which means it is the same as the bundle packaged by webpack.

Secondly, how does umd reference modules? When you don't use a module engine like requirejs, the module file will be imported directly through the script tag. For example, if you introduce multiple bundle files packaged by webpack at the same time, between these files, they actually reference each other through the global mode. In fact, an object is hung on the window and used directly in the second bundle file. This object hung on the window can be used as a global variable. It is said above that vue follows umd, so when you introduce vue and your own bundle file through two script tags, you can reference vue through window.Vue.

Again, how should you reference vue introduced by the script tag in your bundle? Just use the externals from the netizen above. You need to build an externals rule to reference this vue. For how to use externals, you can see the webpack official website, but the explanation on the official website is too simple. Based on the examples on the official website, I wrote a blog about externals to explain in detail. If you are interested, you can read it Down. In your case, externals should contain:

{
    externals: [
        {
            vue: 'Vue',
            jquery: 'jQuery',
            ...
        }
        ...
    ]
}

The above is part of the webpack configuration, use it like this in your source code:

import vue from 'vue'

That’s it. In the packaged bundle file, you can see that in global mode, the global variable Vue will be assigned.

黄舟

Extract vue vuex;

 entry: {
    'vue': ['vue,''vuex']
  },

Write in plugins:

const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
new CommonsChunkPlugin({ name: ['vue'], filename: '文件夹名/[name].js'}),

In this way, no matter whether you require('vue') or not, vue, vuex, etc. will be generated into a separate 文件夹名/vue.js
, and the content contained in this vue.js will not be packaged in your other webpack entry js files.

迷茫

Use externals, still use require

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template