Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue项目配置externals应用CDN文件 #32

Open
jiangshanmeta opened this issue Sep 3, 2020 · 0 comments
Open

vue项目配置externals应用CDN文件 #32

jiangshanmeta opened this issue Sep 3, 2020 · 0 comments

Comments

@jiangshanmeta
Copy link
Owner

项目做多了发现大部分项目都用到了Vue、Vue-Router、axios,然而这几个库每个项目都是独立打包的,所以想把这几个库独立出来。

在vue.config.js中

configureWebpack (config) {
    // 生产环境需要external
    if (process.env.NODE_ENV === 'production') {
        config.externals = {
            vue: 'Vue',
            'vue-router': 'VueRouter',
            axios: 'axios',
        };
    }
},

在html中我们需要配置CDN地址,为了方便起见也是先在vue.config.js中配置:

chainWebpack: config => {
    config
        .plugin('html')
        .tap(args => {
            if (process.env.NODE_ENV === 'production') {
                // 在html中通过htmlWebpackPlugin.options.externals访问
                args[0].externals = [
                    '/external/vue.js',
                    '/external/vue-router.js',
                    '/external/axios.js',
                ];
            }
            return args;
        })
        .end();
},

然后在html中:

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <% if (htmlWebpackPlugin.options.externals) { %>
        <% for (var i in htmlWebpackPlugin.options.externals) { %>
        <script src="<%= htmlWebpackPlugin.options.externals[i] %>" ></script>
        <% } %>
    <% } %>
    <title>external</title>
</head>

另外由于并没有真CDN,但是多个相关vue项目部署在同一个域名下,所以在该域名下建一个external目录,共有的都放在这个目录下。

const path = require('path');
// node版本的cp
const cp = require('cp');
function cpPromise(src,dest){
    return new Promise((resolve,reject)=>{
        cp(src,dest,(err)=>{
            if(err){
                reject(err);
                return
            }
            resolve();
        });
    });
}
const prefix = path.join(__dirname,'../external')
Promise.all([
    cpPromise(path.join(__dirname,'../node_modules/vue/dist/vue.runtime.min.js'),prefix+'/vue.js'),
    cpPromise(path.join(__dirname,'../node_modules/vue-router/dist/vue-router.min.js'),prefix+'/vue-router.js'),
    cpPromise(path.join(__dirname,'../node_modules/axios/dist/axios.min.js'),prefix+'/axios.js'),
]).then(()=>{
    console.log('external copyed')
}).catch((e)=>{
    console.log(e);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant