搭建工程
本次抛弃了npm
,使用yarn
来管理依赖包。后面的命令都是基于yarn
的,npm
的基本也是下面的流程,只不过命令上稍有区别。
项目目录结构
|--config // 其他配置,如webpack等
|--example // 示例
|--lib // 组件
|--src // script代码
|--test // 单元测试
|--.gitignore // git配置
|--.npmignore // npm发布配置
|--karma.conf.js // 单元测试配置文件
|--package.json // 包依赖
|--README.md // 项目说明
|--yarn.lock // yarn安装依赖包生成的文件
example
示例工程,就使用vue-cli
生成一个普通的工程即可;- 组件中如果有依赖其他的包,使用
yarn add xxx
; - 如果是测试的过程中用到的包,使用
yarn add --dev xxx
安装,这样可以避免别人安装你的组件的时候会把测试的依赖包也给下载下来。
本地调试
- 命令行进入项目根目录;
- 执行
yarn link
可以看到如下输出
success Registered "xxx".
info You can now run `yarn link "xxx"` in the projects where you want to use this package and it will be used instead.
✨ Done in 0.07s.
- 进入
example
目录,执行yarn link xxx
,然后运行example
即可调试当前组件库。
集成单元测试
我选用了
karma+jasmine
来做单元测试,主要是用来测试自己编写的一些js
函数。
安装karma-cli
yarn global add karma-cli
安装karma
和必要的插件
// karma
yarn add --dev karma
// 其他插件
yarn add --dev karma-jasmine karma-chrome-launcher jasmine-core
// 运行测试
karma start
定制配置文件
这里我直接摘出官网的配置命令。注意,这里直接
karma init
则会生成一个karma.conf.js
文件,配置也是默认的配置。
$ karma init my.conf.js
Which testing framework do you want to use?
Press tab to list possible options. Enter to move to the next question.
> jasmine
Do you want to use Require.js?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no
Do you want to capture a browser automatically?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
> Firefox
>
What is the location of your source and test files?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Press Enter to move to the next question.
> *.js
> test/**/*.js
>
Should any of the files included by the previous patterns be excluded?
You can use glob patterns, eg. "**/*.swp".
Press Enter to move to the next question.
>
Do you want Karma to watch all the files and run the tests on change?
Press tab to list possible options.
> yes
Config file generated at "/Users/vojta/Code/karma/my.conf.js".
集成webpack
安装依赖包
yarn add --dev karma-webpack webpack
修改配置文件
// karma.conf.js
module.exports = (config) => {
config.set({
// ... normal karma configuration
files: [
// all files ending in "_test"
{ pattern: 'test/*.test.js', watched: false },
{ pattern: 'test/**/*.test.js', watched: false }
// each file acts as entry point for the webpack configuration
],
preprocessors: {
// add webpack as preprocessor
'test/*_test.js': [ 'webpack' ],
'test/**/*.test.js': [ 'webpack' ]
},
webpack: {
// karma watches the test entry points
// (you don't need to specify the entry option)
// webpack watches dependencies
// webpack configuration
},
webpackMiddleware: {
// webpack-dev-middleware configuration
// i. e.
stats: 'errors-only'
}
})
}
未完持续。。。