React导入styled-components的createGlobalStyle报import模块外使用错误
问题说明
触发报错:SyntaxError: Cannot use import statement outside a module
问题触发场景:从styled-components中导入createGlobalStyle时出现该报错,已尝试在package.json中添加"type": "module"配置,未生效。
涉及组件:GlobalStyle组件,目前在login.jsx、index.jsx两个文件中被引入使用。
相关代码
GlobalStyle.jsx
import { createGlobalStyle } from "styled-components"; // eslint-disable-next-line import React from 'react'; const GlobalStyle = createGlobalStyle` body { width: 100%; margin: 0; } `; export default GlobalStyle;
package.json
{ "name": "dev-lio", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.4", "@testing-library/react": "^13.3.0", "@testing-library/user-event": "^13.5.0", "react": "^18.1.0", "react-dom": "^18.1.0", "react-router-dom": "^6.3.0", "react-scripts": "^5.0.1", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "babel-plugin-styled-components": "^2.0.7" } }
login.jsx
import React from 'react' import GlobalStyle from '../../components/GlobalStyle'; import GlobalFonts from '../../fonts/fonts' import LoginForm from '../../components/LoginForm'; const Login = () => { return ( <div> <LoginForm /> <GlobalFonts /> <GlobalStyle /> </div> ) } export default Login;
index.jsx
import React from 'react' import GlobalStyle from '../../components/GlobalStyle'; import Header from '../../components/Header'; import Profile from '../../components/Profile'; import GlobalFonts from '../../fonts/fonts'; const Main = () => { return ( <div> <Header /> <Profile /> <GlobalFonts /> <GlobalStyle /> </div> ) } export default Main;
解决方法
- 第一步先删掉
package.json里手动加的"type": "module"配置。Create React App脚手架默认的模块解析规则不支持这个配置,加了之后会和babel、webpack的内置逻辑冲突,直接触发导入语法报错。 - 检查依赖安装情况:当前依赖列表里只有babel的styled-components插件,没装
styled-components核心包,执行安装命令:
用yarn的话执行:npm install styled-componentsyarn add styled-components - 安装完如果还报错,直接删掉项目根目录下的
node_modules文件夹和锁文件(npm对应package-lock.json,yarn对应yarn.lock),重新执行npm install或者yarn安装全部依赖,再启动项目即可。 - 额外排查点:确认所有组件文件后缀为
.jsx/.js,组件导入路径拼写正确,没有把文件放错目录。
内容的提问来源于stack exchange,提问作者hyehye
相关产品推荐
相关产品推荐

