programing

vuejs 컴포넌트에서 npm 패키지를 생성하여 로컬에서 테스트하는 올바른 방법은 무엇입니까?

copyandpastes 2022. 8. 16. 22:02
반응형

vuejs 컴포넌트에서 npm 패키지를 생성하여 로컬에서 테스트하는 올바른 방법은 무엇입니까?

먼저 vue-cli에서 테스트 컨테이너로 vuejs 프로젝트를 비계화했습니다.그런 다음 npm 패키지를 만듭니다."vue-npm-example"로컬 환경의 Vuejs 컴포넌트에서 위 테스트 프로젝트로 Import할 수 있습니다.

패키지에는

나는 달렸다npm link그리고 프로젝트에서는npm link vue-npm-example,

예.표시하다

<template>
    <div id="vue-npm-example">
        <h1>{{ msg }}</h1>
    </div>
</template>

<script>
    export default {
        name: 'vue-npm-example',
        data() {
            return {
                msg: "Welcome to Your Vue.js App"
            }
        },
        mounted() {
            console.log('this is in compoennt file')
        }
    };
</script>

<style lang="scss">
</style>

main.discloss.main.discloss.

import Example from './components/Example.vue'
export function install(Vue, options) {
    options = {
        installComponents: true
      }
    if (options.installComponents) {
        Vue.component('vuejs-example', Example)
    }    
}
export default Example

webpack.config.syslog

let path = require('path')
let webpack = require('webpack')
function resolve (dir) {
    return path.join(__dirname, '..', dir)
  }

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'index.js'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'vue-style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.scss$/,
                use: [
                    'vue-style-loader',
                    'css-loader',
                    'sass-loader'
                ]
            },
            {
                test: /\.sass$/,
                use: [
                    'vue-style-loader',
                    'css-loader',
                    'sass-loader?indentedSyntax'
                ]
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    loaders: {
                        // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
                        // the "scss" and "sass" values for the lang attribute to the right configs here.
                        // other preprocessors should work out of the box, no loader config like this necessary.
                        'scss': [
                            'vue-style-loader',
                            'css-loader',
                            'sass-loader'
                        ],
                        'sass': [
                            'vue-style-loader',
                            'css-loader',
                            'sass-loader?indentedSyntax'
                        ]
                    }
                    // other vue-loader options go here
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]?[hash]'
                }
            }
        ]
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.common.js',
            '@': resolve('src')
        },
        extensions: ['*', '.js', '.vue', '.json']
    },
    devServer: {
        historyApiFallback: true,
        noInfo: true,
        overlay: true
    },
    performance: {
        hints: false
    },
    devtool: '#eval-source-map',
    node: {
        fs: 'empty'
    },
    watch: true
}

if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = '#source-map'
    // http://vue-loader.vuejs.org/en/workflow/production.html
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        // new webpack.optimize.UglifyJsPlugin({
        //     sourceMap: true,
        //     compress: {
        //         warnings: false
        //     }
        // }),
        new webpack.LoaderOptionsPlugin({
            minimize: true
        })
    ])
}

그리고 테스트 프로젝트에서는

import Vue from 'vue'
import Example from 'vue-npm-example'
Vue.component('example', Example)

사용법을 알 수식하다

<example></example>

에러가 발생했습니다.

[Vue warn]: Failed to mount component: template or render function not defined.

패키지와 프로젝트의 웹 팩 구성 파일에서 vue 에일리어스를 설정합니다.패키지의 main.js에서 console.log()를 실행하면 테스트 프로젝트에 로그인하기 때문에 패키지가 올바르게 도입되었습니다.하지만 아무리 노력해도 테스트 프로젝트에서는 패키지의 부품이 작동하지 않습니다.

좋은 의견이라도 있나?

npm 링크는 심볼링크를 만듭니다만, 로컬 npm 패키지를 Import 할 때는 패키지의 풀주소를 지정해야 합니다.저 같은 경우에는...import customComponent from './node_modules/custom-component/dist/index.js' custom-component'에서 custom Component를 Import합니다.

나는 사용하고 싶다npm pack대신 (사용의 몇 가지 단점)npm linknpm 패키지를 로컬로 테스트하려면http://https://blog.vcarl.com/testing-packages-before-publishing/) 를 참조해 주세요.

패키지 내

달려.npm pack

프로젝트 내

달려.npm install (path-to-package)/package-name-0.0.0.tgz

그런 다음 패키지를 Import/설치합니다.main.js:

import MyPackage from 'package-name'

// This runs your 'install' method which registers your component globally with Vue.component(...)
Vue.use(MyPackage);

유용한 링크

npm용 Vue 컴포넌트 패키지화:https://vuejs.org/v2/cookbook/packaging-sfc-for-npm.html

Vue npm 실사 : https://www.telerik.com/blogs/vuejs-how-to-build-your-first-package-publish-it-on-npm

글로벌 컴포넌트 등록: https://vuejs.org/v2/guide/components-registration.html#Global-Registration

언급URL : https://stackoverflow.com/questions/49909983/what-is-correct-way-to-create-a-npm-package-from-a-vuejs-component-and-testing-o

반응형