Github source code: https://github.com/duongdam/classfunc-react-snowpack
Hôm nay mình xin chia sẻ cách để tạo 2 môi trường phát triển production và stg khi build 1 dự án bằng snowpack. Mình mở đầu 1 câu là thằng snowpack build rất nhanh, nhanh lắm luôn ấy.
Trước tiên, các bạn sẽ tạo các file .env
như sau:
.env.production
, .env.stg
, .env.development
Ở snowpack phiên bản cho React hỗ trợ mình Plugin @snowpack/plugin-dotenv
Bạn cài đặt bằng yarn add --dev @snowpack/plugin-dotenv
và thêm vào phần plugins của snowpack.config.js or snowpack.config.json
.
"plugins": ["@snowpack/plugin-webpack", "@snowpack/plugin-dotenv", "@snowpack/plugin-react-refresh"], "scripts": { "bundle:*": "@snowpack/plugin-webpack" },
Để build các môi trường khác nhau, bạn chỉ cần thêm tiền tố NODE_ENV=['envNAme']
trước snowpack build
, dưới đây là ví dụ của mình:
{ "scripts": { "start": "snowpack dev", "start-stg": "NODE_ENV=stg snowpack dev", "build-stg": "NODE_ENV=stg snowpack build", "build-prod": "NODE_ENV=production snowpack build" } }
Ngoai ra bạn có thể tuỳ biến môi trường ở chế độ development khi thêm tiền tố NODE_ENV=['envNAme']
trước snowpack dev
, rất hay và tiện lợi phải không nào!
Biến môi trường và cách sử dụng
// `import.meta.env` - Read process.env variables in your web app fetch(`${import.meta.env.SNOWPACK_PUBLIC_API_URL}/users`).then(...) // Supports destructuring as well: const {SNOWPACK_PUBLIC_API_URL} = import.meta.env; fetch(`${SNOWPACK_PUBLIC_API_URL}/users`).then(...) // Instead of `import.meta.env.NODE_ENV` use `import.meta.env.MODE` if (import.meta.env.MODE === 'development') { // ...
Chúc các bạn thành công! cùng nhau chia sẻ thật nhiều kiến thức thú vị nhé.
Tài liệu tham khảo: