你可以使用 Webpack 在你的项目中引入并打包 UIkit 的 JavaScript。
为了完成基本的项目搭建,我们将创建以下文件:
app/
index.js
index.html
package.json以下命令会创建并填充 package.json 文件。其中包含供 pnpm 使用的依赖,我们引入了 UIkit 和 Webpack。
mkdir uikit-webpack && cd uikit-webpack
pnpm init
pnpm add uikit
pnpm add --dev webpack作为项目 JavaScript 的入口文件,创建 app/index.js,内容如下。
import UIkit from 'uikit';
import Icons from 'uikit/dist/js/uikit-icons';
// loads the Icon plugin
UIkit.use(Icons);
// components can be called from the imported UIkit reference
UIkit.notification('Hello world.');这样,你无需在 HTML 中引入 UIkit 的 JavaScript 文件,也能获得对 UIkit 的引用。取而代之的是,我们可以引入由 Webpack 生成的完整 bundle。创建主 HTML 文件 index.html,内容如下。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<link rel="stylesheet" href="node_modules/uikit/dist/css/uikit.min.css">
</head>
<body>
<div class="uk-container">
<div class="uk-card uk-card-body uk-card-primary">
<h3 class="uk-card-title">Example headline</h3>
<button class="uk-button uk-button-default" uk-tooltip="title: Hello World">Hover</button>
</div>
</div>
<script src="dist/bundle.js"></script>
</body>
</html>注意 为简洁起见,这里引入的是预构建的 CSS。在实际项目中,你多半需要构建 Less 文件并引入编译后的 CSS。
要配置 Webpack 把 app/index.js 编译为 dist/bundle.js,创建 webpack.config.js 文件,内容如下。
var path = require('path');
module.exports = {
entry: './app/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};现在,在项目的主目录中运行 Webpack。
./node_modules/.bin/webpack # Run webpack from local project installation
.\node_modules\.bin\webpack # Run webpack on Windows
webpack # If you installed webpack globally至此,项目的基本搭建已完成。在浏览器中打开 index.html,确认页面上已经应用了基本的 UIkit 样式。如果打包成功,页面顶部应弹出一条通知,按钮在悬停时应显示一条提示信息。