Javascript 从根导入 ES6
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29755065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES6 import from root
提问by Alias
I'm currently playing around with React Native. I'm trying to structure my app, however it's starting to get messy with imports.
我目前正在玩 React Native。我正在尝试构建我的应用程序,但是它开始变得与导入混乱。
--app/
-- /components
-- Loading.js
-- index.ios.js
Now, within my index.ios.jsi'm able to simply do:
现在,在我的范围内,我index.ios.js可以简单地执行以下操作:
import Loading from './components/Loading';
import Loading from './components/Loading';
However, when I start to create more components, with a deeper directory struture, it starts to get messy:
然而,当我开始创建更多的组件时,使用更深的目录结构,它开始变得混乱:
import Loading from '.../../../../components/Loading';
import Loading from '.../../../../components/Loading';
I understand the preferred solution would be to make private npm modules for things, but that's overkill for a small project.
我知道首选的解决方案是为事物制作私有的 npm 模块,但这对于一个小项目来说太过分了。
You could do a global.requireRoottype solution on the browser, but how do I implement this with import?
你可以global.requireRoot在浏览器上做一个类型的解决方案,但我如何通过导入来实现呢?
采纳答案by Michael J. Zoidl
Had the same issue with React. So i wrote some plugin for babel which make it possible to import the modules from the root perspective - the paths are not shorter - but it's clear what you import.
React 也有同样的问题。所以我为 babel 写了一些插件,它可以从根的角度导入模块 - 路径不短 - 但很清楚你导入了什么。
So instead of:
所以而不是:
import 'foo' from '../../../components/foo.js';
You can use:
您可以使用:
import 'foo' from '~/components/foo.js';
回答by Velidan
If you are using Webpack you can configure it via the resolveproperty to resolve a your import path.
如果你使用 Webpack,你可以通过resolve属性配置它来解析你的导入路径。
Webpack 1
网络包 1
resolve: {
root: [
path.resolve(__dirname + '/src')
]
}......
Webpack 2
网络包 2
resolve: {
modules: [
path.resolve(__dirname + '/src'),
path.resolve(__dirname + '/node_modules')
]
}.....
After that you can use
之后你可以使用
import configureStore from "store/configureStore";
instead of the:
而不是:
import configureStore from "../../store/configureStore";
Webpack will configure your import path from the passed resolve param.
Webpack 将从传递的解析参数配置您的导入路径。
The same stuff you can do with System.js loader but with it's own config param (it's can be mapor path. Check it in the System.js documentation) (if you would like to use it. It's mostly for a Angular 2 case. But I suggest: don't use standard System.js even if you are working with ng2. Webpack is much better).
你可以用 System.js 加载器做同样的事情,但它有自己的配置参数(它可以是 map或path。在 System.js 文档中检查它)(如果你想使用它。它主要用于 Angular 2 案例. 但我建议:即使你使用的是 ng2,也不要使用标准的 System.js。Webpack 更好)。
回答by Alexander Derck
With webpack you can also make paths starting with for example ~resolve to the root, so you can use import Loading from '~/components/Loading';:
使用 webpack,您还可以使路径以例如~解析为根开始,因此您可以使用import Loading from '~/components/Loading';:
resolve: {
extensions: ['.js'],
modules: [
'node_modules',
path.resolve(__dirname + '/app')
],
alias: {
['~']: path.resolve(__dirname + '/app')
}
}
The trick is using the javascript bracket syntax to assign the property.
诀窍是使用 javascript 括号语法来分配属性。
回答by keemor
In Webpack 3the config is slightly diffrent:
在Webpack 3 中,配置略有不同:
import webpack from 'webpack';
import {resolve} from 'path';
...
...
module: {
loaders: [
{
test: /\.js$/,
use: ["babel-loader"]
},
{
test: /\.scss$|\.css$/,
use: ["style-loader", "css-loader", "sass-loader"]
}
]
},
resolve: {
extensions: [".js"],
alias: {
["~"]: resolve(__dirname, "src")
}
},
回答by FMD
I just checked out a React project which is more than 6 months old and for some reasons my imports no longer worked. I tried the first answer:
我刚刚检查了一个超过 6 个月的 React 项目,由于某些原因,我的导入不再有效。我尝试了第一个答案:
import 'foo' from '~/components/foo.js';
Unfortunately this did not work.
不幸的是,这不起作用。
I added an .envfile in the root of my project at the same level as my package.json. I added the following line to that file and this fixed my imports in my project.
我.env在项目的根目录中添加了一个与我的package.json. 我将以下行添加到该文件中,这修复了我在项目中的导入。
NODE_PATH=src/
回答by Scotty Jamison
If you're using Create-React-App, you just need to change the environmental variable NODE_PATHto contain the root of your project.
如果您使用的是Create-React-App,则只需更改环境变量NODE_PATH以包含项目的根目录。
In your config.json do the following change to set this variable before running the react-scripts commands:
在您的 config.json 中,在运行 react-scripts 命令之前进行以下更改以设置此变量:
"scripts": {
"start": "cross-env NODE_PATH=. react-scripts start",
"build": "cross-env NODE_PATH=. react-scripts build",
"test": "cross-env NODE_PATH=. react-scripts test",
"eject": "react-scripts eject"
},
We're using the npm library cross-envbecause it works on unix and windows. The syntax is cross-env var=value command.
我们使用 npm 库cross-env因为它适用于 unix 和 windows。语法是cross-env var=value command.
Now instead of import module from '../../my/module'we can do import module from 'src/my/module'
现在import module from '../../my/module'我们可以做而不是import module from 'src/my/module'
Extra details on implementation
关于实施的额外细节
Its important to note that cross-env's scope is limited to the command it executes, so cross-env var=val command1 && command2will only have var set during command1. Fix this if needed by doing cross-env var=val command1 && cross-env var=val command2
需要注意的是,cross-env 的范围仅限于它执行的命令,因此cross-env var=val command1 && command2只会在 command1 期间设置 var。如果需要,请通过执行此操作来解决此问题cross-env var=val command1 && cross-env var=val command2
create-react-app gives precedence to folders in node_modules/ over whats in NODE_PATH, which is why we're setting NODE_PATH to "." instead of "./src". Using "." requires all absolute imports to start with "src/" which means there should never be a name conflict, unless you're using some node_module called src.
create-react-app 将 node_modules/ 中的文件夹优先于 NODE_PATH 中的文件夹,这就是我们将 NODE_PATH 设置为“.”的原因。而不是“./src”。使用 ”。” 要求所有绝对导入都以“src/”开头,这意味着永远不应该有名称冲突,除非您使用一些名为 src 的 node_module。
(Note of caution: The solution described above replacesthe variable NODE_PATH. Ideally we would append to it if it already exists. NODE_PATH is a ":" or ";" separated list of paths, depending on if its unix or windows. If anyone finds a cross-platform solution to do this, I can edit my answer.)
(注意:上面描述的解决方案替换了变量 NODE_PATH。理想情况下,如果它已经存在,我们会附加到它。NODE_PATH 是一个“:”或“;”分隔的路径列表,取决于它的unix还是windows。如果有人找到一个跨平台的解决方案来做到这一点,我可以编辑我的答案。)
回答by Craig Myles
If you're using Create React App you can add paths.appSrcto resolve.modulesin config/webpack.config.dev.jsand config/webpack.config.prod.js.
如果您使用的是 Create React App,则可以添加paths.appSrc到resolve.modulesinconfig/webpack.config.dev.js和config/webpack.config.prod.js.
From:
从:
resolve: {
modules: ['node_modules', paths.appNodeModules].concat(...
To:
到:
resolve: {
modules: [paths.appSrc, 'node_modules', paths.appNodeModules].concat(...
Your code would then work:
然后您的代码将起作用:
import Loading from 'components/Loading';

