使用Webpack v4.5引入Bootstrap CSS时遇解析错误求助
Hey there, I’ve run into this exact issue before—Webpack doesn’t natively understand CSS syntax, so you need to add the right loaders to process .css files like Bootstrap’s. Let’s get this sorted step by step:
Step 1: Install Required Loaders
First, you need two key loaders to handle CSS files:
css-loader: Parses CSS files (handles@import,url(), and other CSS-specific syntax)style-loader: Injects the parsed CSS into the DOM via<style>tags
Install them using npm or yarn:
# Using npm npm install --save-dev css-loader style-loader # Using yarn yarn add -D css-loader style-loader
Step 2: Update Your Webpack Config
Open your webpack.config.js file and add a dedicated rule for .css files in the module.rules section:
module.exports = { // Keep your existing entry, output, and other configs here... module: { rules: [ // Add this rule to process CSS files { test: /\.css$/, use: [ 'style-loader', // Injects processed CSS into the browser's DOM 'css-loader' // Parses the raw CSS code ] } ] } };
Optional: Optimize for Production
If you’re building for production, it’s better to extract CSS into standalone files instead of injecting them into the DOM. You can replace style-loader with mini-css-extract-plugin for this:
- Install the plugin:
npm install --save-dev mini-css-extract-plugin
- Update your Webpack config:
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { plugins: [new MiniCssExtractPlugin()], // Creates separate CSS files module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, // Extracts CSS to files 'css-loader' ] } ] } };
Verify the Fix
After making these changes, re-run your Webpack build command. The "Unexpected token" error should disappear, and Bootstrap’s styles should load correctly in your project.
内容的提问来源于stack exchange,提问作者Geraint

