在 ts 环境中加载 css 样式和图片都需要简单的配置,配置流程如下:
npm i --save-dev css-loader style-loader
webpack.config.js
文件中配置识别 css module 的配置项:module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{
test: /\.tsx?$/, loader: "ts-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre", test: /\.js$/, loader: "source-map-loader" },
// Load .css files
{
test: /\.css$/, use: ["style-loader", "css-loader"] },
]
},
这样就可以在文件加载 css 样式了,简单实用:)
import "styles.css"; // 不要忘记了 .css 的后缀
npm i --save-dev file-loader
webpack.config.js
文件中配置加载图片的配置项:module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{
test: /\.tsx?$/, loader: "ts-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre", test: /\.js$/, loader: "source-map-loader" },
// Load .css files
{
test: /\.css$/, use: ["style-loader", "css-loader"] },
//Load image
{
test: /\.(jpg|jpeg|png|svg)$/, loader: 'file-loader', options: {
name: 'images/[hash].[ext]' } },
]
},
images.d.ts
文件,并且将该文件放在 tsconfig.json
同级路径下,images.d.ts
内容:declare module "*.svg";
declare module "*.png";
declare module "*.jpg";
declare module "*.jpeg";
declare module "*.gif";
declare module "*.bmp";
declare module "*.tiff";
这样就可以识别所有不同后缀名的文件了
import img from "../public/images/homephoto.png";